Android Club – Tic Tac Toe game step-by-step instruction

In this tutorial, I will show how to build Tic Tac Toe console game in Java.

1. First of all, we create our class. Let’s call it – Game. Inside of our class, create main method where our game starts.

public class Game {
    public static void main(String[] args) {
       
    }
}

2. Create static String ArrayList where will hold our Xs and Os. If it is empty(no X and no O), it will show element index. ArrayList should be class variable to make it available in our other methods. Fill ArrayList with index numbers using for loop inside main method.

static ArrayList<String> numbers;
   
    public static void main(String[] args) {
       
        elements = new ArrayList<String>();
        for (int i = 0; i <= 8; i++) {
            elements.add(String.valueOf(i));
        }
       
    }

3. Let’s create method which helps us to show Tic Tac Toe in this form
0 | 1 | 2
3 | 4 | 5
6 | 7 | 8

    private static void showTable() {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < numbers.size(); i++) {
            String position = numbers.get(i);
            sb.append(position);
           
            if(i%3==2)
            {
                sb.append("\n");
            }
            else
            {
                sb.append(" | ");
            }
           
        }
        System.out.println(sb.toString());
    }

4. Create static final Strings for X and O;

    static final String x = "X";
    static final String o = "O";

Create class variable boolean player1. If player1 is true, so player 1’s turn, if player1 is false, now player 2 will play.

    static boolean player1 = true;

Let’s create scanner using which we will get user input.

    static Scanner scanner;
   
    public static void main(String[] args) {
        // initialize scanner
        scanner = new Scanner(System.in);

Create another method, which will be used to set user’s mark(X or O up to player) to position.

    private static void setUserValue() {
        if(player1)
        {
            System.out.println("X - Player 1's turn");
            System.out.println("Enter position");
           
        }
        else
        {
            System.out.println("O - Player 2's turn");
            System.out.println("Enter position");
        }
       
        int position = scanner.nextInt();
       
        if(numbers.get(position).equals(x)||numbers.get(position).equals(o))
        {
            System.out.println("This position is already taken");
        }
        else if(player1)
        {
            numbers.set(position, x);
            player1 = false;
        }
        else
        {
            numbers.set(position, o);
            player1 = true;
        }
    }

5. Now we will create method which identifies winner. These method will return boolean value, which represents winner is found or not. True – if winner found, false – not found.
In this method we create 2 ArrayLists, where we can save positions for Xs and Os. We fill these ArrayLists from numbers ArrayList. For example, if index 4 is X, then we add 4 to xxx ArrayList. Then we create Array of winning combinations in order to find winner.

    private static boolean findWinner()
    {
       
        ArrayList<String> xxx = new ArrayList<String>();
        ArrayList<String> ooo = new ArrayList<String>();
       
        for (int i = 0; i < numbers.size(); i++) {
            String num = numbers.get(i);
            if(num.equals(x))
            {
                xxx.add(String.valueOf(i));
            }
            if(num.equals(o))
            {
                ooo.add(String.valueOf(i));
            }
        }
       
        String[] win0 = {"0","1","2"};
        String[] win1 = {"3","4","5"};
        String[] win2 = {"6","7","8"};
        String[] win3 = {"0","3","6"};
        String[] win4 = {"1","4","7"};
        String[] win5 = {"2","5","8"};
        String[] win6 = {"0","4","8"};
        String[] win7 = {"2","4","6"};
       
        String[][] wins = {win0, win1, win2, win3, win4, win5, win6, win7};
       
        for (int i = 0; i < wins.length; i++) {
            String[] win = wins[i];
           
            int xCount = 0;
            int oCount = 0;
            for (int j = 0; j < win.length; j++) {
                String pos = win[j];
                if(xxx.contains(pos))
                {
                    xCount++;
                }
                if(ooo.contains(pos))
                {
                    oCount++;
                }
            }
            if(xCount==3)
            {
                System.out.println("Winner is Player 1");
                return false;
            }
            if(oCount==3)
            {
                System.out.println("Winner is Player 2");
                return false;
            }
           
        }
        return true;
    }

6. Last step in our game is to create general logic using our methods. We will ask user to choose position till we do not found winner. In each iteration we show table and ask user enter position.

        while(findWinner())
        {
            showTable();
            setUserValue();
        }

That’s it! Now you can play Tic Tac Toe on Console! However, we did not write logic for situation when winner is not determined. I think it should not be hard to write it yourself. Good luck!

Here you can see whole code:

import java.util.ArrayList;
import java.util.Scanner;


public class Game {

    static final String x = "X";
    static final String o = "O";
    public static ArrayList<String> numbers;
    static boolean player1 = true;
    static Scanner scanner;
   
    public static void main(String[] args) {
       
        scanner = new Scanner(System.in);
       
        numbers = new ArrayList<String>();
        for (int i = 0; i <= 8; i++) {
            numbers.add(String.valueOf(i));
        }
       
        while(findWinner())
        {
            showTable();
            setUserValue();
        }
       
    }
   
    private static boolean findWinner()
    {
       
        ArrayList<String> xxx = new ArrayList<String>();
        ArrayList<String> ooo = new ArrayList<String>();
       
        for (int i = 0; i < numbers.size(); i++) {
            String num = numbers.get(i);
            if(num.equals(x))
            {
                xxx.add(String.valueOf(i));
            }
            if(num.equals(o))
            {
                ooo.add(String.valueOf(i));
            }
        }
       
        String[] win0 = {"0","1","2"};
        String[] win1 = {"3","4","5"};
        String[] win2 = {"6","7","8"};
        String[] win3 = {"0","3","6"};
        String[] win4 = {"1","4","7"};
        String[] win5 = {"2","5","8"};
        String[] win6 = {"0","4","8"};
        String[] win7 = {"2","4","6"};
       
        String[][] wins = {win0, win1, win2, win3, win4, win5, win6, win7};
       
        for (int i = 0; i < wins.length; i++) {
            String[] win = wins[i];
           
            int xCount = 0;
            int oCount = 0;
            for (int j = 0; j < win.length; j++) {
                String pos = win[j];
                if(xxx.contains(pos))
                {
                    xCount++;
                }
                if(ooo.contains(pos))
                {
                    oCount++;
                }
            }
            if(xCount==3)
            {
                System.out.println("Winner is Player 1");
                return false;
            }
            if(oCount==3)
            {
                System.out.println("Winner is Player 2");
                return false;
            }
           
        }
        return true;
    }
   
    private static void setUserValue() {
        if(player1)
        {
            System.out.println("X - Player 1's turn");
            System.out.println("Enter position");
           
        }
        else
        {
            System.out.println("O - Player 2's turn");
            System.out.println("Enter position");
        }
       
        int position = scanner.nextInt();
       
        if(numbers.get(position).equals(x)||numbers.get(position).equals(o))
        {
            System.out.println("This position is already taken");
        }
        else if(player1)
        {
            numbers.set(position, x);
            player1 = false;
        }
        else
        {
            numbers.set(position, o);
            player1 = true;
        }
    }
   
    private static void showTable() {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < numbers.size(); i++) {
            String position = numbers.get(i);
            sb.append(position);
           
            if(i%3==2)
            {
                sb.append("\n");
            }
            else
            {
                sb.append(" | ");
            }
           
        }
        System.out.println(sb.toString());
    }
   
}

Android Club – Tic Tac Toe game source code

import java.util.ArrayList;
import java.util.Scanner;

public class TicTacToeGame {
   
    static final String x = "X";
    static final String o = "O";
    static ArrayList<String> numbers;
    static Scanner scanner;
    static boolean player1 = true;
   
    public static void main(String[] args) {
       
        scanner = new Scanner(System.in);
       
        numbers = new ArrayList<String>();
        for (int i = 0; i <= 8; i++) {
            numbers.add(String.valueOf(i));
        }
       
        while(findWinner())
        {
            showTable();
            setUserValue();
        }
    }
   
    private static boolean findWinner()
    {
       
        ArrayList<String> xxx = new ArrayList<String>();
        ArrayList<String> ooo = new ArrayList<String>();
       
        for (int i = 0; i < numbers.size(); i++) {
            String num = numbers.get(i);
            if(num.equals(x))
            {
                xxx.add(String.valueOf(i));
            }
            if(num.equals(o))
            {
                ooo.add(String.valueOf(i));
            }
        }
       
        String[] win0 = {"0","1","2"};
        String[] win1 = {"3","4","5"};
        String[] win2 = {"6","7","8"};
        String[] win3 = {"0","3","6"};
        String[] win4 = {"1","4","7"};
        String[] win5 = {"2","5","8"};
        String[] win6 = {"0","4","8"};
        String[] win7 = {"2","4","6"};
       
        String[][] wins = {win0, win1, win2, win3, win4, win5, win6, win7};
       
        for (int i = 0; i < wins.length; i++) {
            String[] win = wins[i];
           
            int xCount = 0;
            int oCount = 0;
            for (int j = 0; j < win.length; j++) {
                String pos = win[j];
                if(xxx.contains(pos))
                {
                    xCount++;
                }
                if(ooo.contains(pos))
                {
                    oCount++;
                }
            }
            if(xCount==3)
            {
                System.out.println("Winner is Player 1");
                return false;
            }
            if(oCount==3)
            {
                System.out.println("Winner is Player 2");
                return false;
            }
           
        }
        return true;
    }

    private static void setUserValue() {
        if(player1)
        {
            System.out.println("X - Player 1's turn");
            System.out.println("Enter position");
           
        }
        else
        {
            System.out.println("O - Player 2's turn");
            System.out.println("Enter position");
        }
       
        int position = scanner.nextInt();
       
        if(numbers.get(position).equals(x)||numbers.get(position).equals(o))
        {
            System.out.println("This position is already taken");
        }
        else if(player1)
        {
            numbers.set(position, x);
            player1 = false;
        }
        else
        {
            numbers.set(position, o);
            player1 = true;
        }
    }

    private static void showTable() {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < numbers.size(); i++) {
            String position = numbers.get(i);
            sb.append(position);
           
            if(i%3==2)
            {
                sb.append("\n");
            }
            else
            {
                sb.append(" | ");
            }
           
        }
        System.out.println(sb.toString());
    }
   
}

Euler Project: Problem 22 Solution

Using names.txt (right click and ‘Save Link/Target As…’), a 46K text file containing over five-thousand first names, begin by sorting it into alphabetical order. Then working out the alphabetical value for each name, multiply this value by its alphabetical position in the list to obtain a name score.

For example, when the list is sorted into alphabetical order, COLIN, which is worth 3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the list. So, COLIN would obtain a score of 938 × 53 = 49714.

What is the total of all the name scores in the file?

Answer: 871198282

public class Problem22 {

    public static void main(String[] args) throws IOException {

        // alphabet
        char[] alphabet = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
                'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
                'w', 'x', 'y', 'z' };
        ArrayList<Character> al_alphabet = new ArrayList<Character>();
        for (int i = 0; i < alphabet.length; i++) {
            al_alphabet.add(alphabet[i]);
        }

        // read file content
        File file = new File("p022_names.txt");
        InputStream in = new FileInputStream(file);
        StringBuilder sb = new StringBuilder();
        while (true) {
            int data = in.read();
            if (data == -1) {
                in.close();
                break;
            } else {
                sb.append((char) data);
            }
        }
        String file_content = sb.toString();

        // names array
        String[] names = file_content.split(",");
        Arrays.sort(names);

        // calculate sum of scores
        int scores_sum = 0;
        for (int i = 0; i < names.length; i++) {

            String name = names[i];
            name = name.substring(1, name.length() - 1);
            name = name.toLowerCase();

            int worth_sum = 0;
            for (int j = 0; j < name.length(); j++) {
                char letter = name.charAt(j);
                int letter_worth = al_alphabet.indexOf(letter) + 1;
                worth_sum += letter_worth;
            }

            int score = (i + 1) * worth_sum;
            scores_sum += score;
        }

        System.out.println(scores_sum);

    }

}