Search code examples
javastringinitializing

String Initializing


I'm creating a TicTacToe game and I've come across an issue with my strings

Code:

import java.util.Scanner;

public class TicTacToe {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        String player1Letter;
        String player2Letter;

        System.out.print("Player 1 Name: ");
        String player1 = input.next();
        System.out.print('\f');

        System.out.print("Player 2 Name: ");
        String player2 = input.next();
        System.out.print('\f');

        System.out.print(player1 + ", Choose X or O: ");
        String letter = input.next();

        if (letter.equalsIgnoreCase("x")) {
            player1Letter = "X";
        } else {
            player2Letter = "O";
        }

        if (letter.equalsIgnoreCase("o")) {
            player1Letter = "O";
        } else {
            player2Letter = "X";
        }

        System.out.print('\f');
        System.out.println("How To");
        System.out.println("-------");
        System.out.println();
        System.out.println(" 1 | 2 | 3 ");
        System.out.println("-----------");
        System.out.println(" 4 | 5 | 6 ");
        System.out.println("-----------");
        System.out.println(" 7 | 8 | 9 ");
        System.out.println();

        while (true) {
            System.out.print("Type 'begin' To Begin: ");
            String begin = input.next();
            if (begin.equalsIgnoreCase("begin")) {
                break;
            } else if (!begin.equals("begin")) {
                System.out.print('\f');
                System.out.println("Incorrect Syntax");
                System.out.println();
            }
        }
        System.out.println(player1 + "'s Turn " + player1Letter);
        System.out.println("-----------------------------------");
        System.out.println();
        System.out.println("   |   |   ");
        System.out.println("-----------");
        System.out.println("   |   |   ");
        System.out.println("-----------");
        System.out.println("   |   |   ");
    }
}

Towards the bottom where it says

System.out.println(player1 + "'s Turn " + player1Letter);

I get the error saying "variable player1Letter might not have been initialized". I created the strings outside of the if-statements and initialized them inside of the if-statement. Now I'm calling it, I can't figure out what's wrong here. Thank you!


Solution

  • change your initialization code like this:

    if (letter.equalsIgnoreCase("x")) {
        player1Letter = "X";
        player2Letter = "O";
    } else {
        player1Letter = "O";
        player2Letter = "X";
    }
    

    so you will initialize both variables always