我創建一個井字遊戲,我遇到一個問題,我的琴絃字符串初始化
代碼:
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(" | | ");
}
}
駛向何方,它說
System.out.println(player1 + "'s Turn " + player1Letter);
我的底部得到錯誤說「變量player1Letter可能沒有被初始化」。我在if語句之外創建了字符串,並在if語句內初始化它們。現在我打電話給我,我無法弄清楚這裏有什麼問題。謝謝!
這將工作,但值得注意的是,例如,如果輸入「z」或「lampshade」,則即使提示要求輸入X或O,也會執行後一種情況。 – Monkeygrinder