import java.util.Scanner;
public class PlayAgain {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean playing = true;
char replayCheck;
do { //start do-while
System.out.print("Play again? (y/n): ");
boolean validInput = false;
while (validInput = false){ //start while
replayCheck = input.next().charAt(0);
switch (replayCheck) { //start switch
case 'y':
case 'Y':
validInput = true;
playing = true;
break;
case 'n':
case 'N':
validInput = true;
playing = false;
break;
default:
System.out.println("Invalid input! please enter (y/n)");
validInput = false;
break;
} //end switch
} //end while
} while (playing = true); //end do-while
System.out.println("Thanks for playing!");
} //end main
} //end class
如果用户输入n/N
程序再次播放,则任何其他输入也一样。逻辑似乎很好,但我得到了#34;指定的值从未使用过"与replayCheck = input.next().charAt(0);
一致,所以我怀疑问题就在那里。
我有点像诺贝尔。欢迎任何建议!
答案 0 :(得分:1)
改变' ='到' =='为了比较,你的代码工作正常:
import java.util.Scanner;
public class PlayAgain {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean playing = true;
char replayCheck;
do { //start do-while
System.out.print("Play again? (y/n): ");
boolean validInput = false;
while (validInput == false){ //start while
replayCheck = input.next().charAt(0);
switch (replayCheck) { //start switch
case 'y':
case 'Y':
validInput = true;
playing = true;
break;
case 'n':
case 'N':
validInput = true;
playing = false;
break;
default:
System.out.println("Invalid input! please enter (y/n)");
validInput = false;
break;
} //end switch
} //end while
} while (playing == true); //end do-while
System.out.println("Thanks for playing!");
} //end main
} //end class
答案 1 :(得分:0)
检查需要:
while (validInput == false) {
....
}
否则,您会将false
分配给validInput
,从而导致false
,从而退出循环。
在Java中,编写此类检查的惯用方法是:
while (!validInput) {
...
}
答案 2 :(得分:0)
问题在于它应该是while循环
while (validInput == false) {}