我想制作一个重复自己的代码,直到用户输入单词Game或单词Balance。我做了一个do while
循环,但是我的while语句出错了。错误是:error3 cannot be resolved into a variable
。有谁知道我的代码有什么问题?
System.out.println("welcome to Roll the Dice!");
System.out.println("What is your name?");
Scanner input = new Scanner(System. in );
String Name = input.nextLine();
System.out.println("Welcome " + Name + "!");
System.out.println("Do you want to play a game or do you want to check your account's balance?");
System.out.println("For the game typ: Game. For you accounts balance typ: Balance");
do {
String Choice = input.nextLine();
String Balance = "Balance";
String Game = "Game";
input.close();
boolean error1 = !new String(Choice).equals(Game);
boolean error2 = !new String(Choice).equals(Balance);
boolean error3 = (error2 || error1) == true;
if (new String(Choice).equals(Game)) {
System.out.println("Start the game!");
}
else if (new String(Choice).equals(Balance)) {
System.out.println("Check the balance");
}
else {
System.out.println("This is not an correct answer");
System.out.println("Typ: Game to start a game. Typ: Balance to see your account's balance");
}
}
while ( error3 == true );
error3
在do
范围内定义。将其声明移到do
范围之外并在其中设置值:
boolean error3 = false;
do {
String Choice = input.nextLine();
String Balance = "Balance";
String Game = "Game";
input.close();
boolean error1 = ! new String(Choice).equals(Game);
boolean error2 = ! new String(Choice).equals(Balance);
error3 = error2 || error1;
另请注意,您可以将(error2 || error1) == true
简化为error2 || error1
。您的while
声明也可以这样做:
while(error3);
你试图在声明它的循环体范围之外读取error3
的值:
while(error3 == true);
只需在循环之前声明它:
boolean error3 = true;
do {
//...
error3 = (error2 || error1) == true;
//...
}
while(error3 == true);
因为你在do-while循环中定义了变量。做这个:
boolean error3=true;
do {
String Choice = input.nextLine();
String Balance = "Balance";
String Game = "Game";
input.close();
boolean error1 = ! new String(Choice).equals(Game);
boolean error2 = ! new String(Choice).equals(Balance);
error3 = (error2 || error1) == true;
if (new String(Choice).equals(Game)){
System.out.println("Start the game!");
}
else if(new String(Choice).equals(Balance)){
System.out.println("Check the balance");
}
else{
System.out.println("This is not an correct answer");
System.out.println("Typ: Game to start a game. Typ: Balance to see your account's balance");
}
}
while(error3 == true);