我知道这段代码编写得非常糟糕(Java和编程的第一天),但我正在编写一个Java代码,它将从用户(骰子)获取输入并从该骰子中生成一个随机数。我添加了一个while循环来询问用户是否想要重新启动程序,但是每次运行它都会告诉我在输入任何内容之前它是无效的输入。请帮忙。
import java.util.Scanner;
import java.util.Random;
public class Java {
public static void main(String args[]){
Scanner input = new Scanner(System.in);
String restartChoice = "y";
while (restartChoice == "y" || restartChoice == "Y"){
int choice;
System.out.println("Please choose which dice you would like to roll. 4/6/12 ");
choice = input.nextInt();
while (choice != 4 && choice != 6 && choice != 12){
System.out.println("That is not a valid input, please try again... ");
choice = input.nextInt();
}
Random rand = new Random();
int value = rand.nextInt(choice) + 1;
System.out.print("You chose to roll the ");
System.out.print(choice);
System.out.print(" sided dice. The number is ");
System.out.println(value);
System.out.println("Would you like to restart? Y/N ");
restartChoice = input.nextLine();
while (restartChoice != "y" && restartChoice != "n" && restartChoice != "y" && restartChoice != "n"){
System.out.println("That is not a valid input. Please try again. ");
restartChoice = input.nextLine();
}
}
}
}
答案 0 :(得分:0)
Scanner#nextInt()
不会使用换行符,导致该字符被传递到循环
while (restartChoice != "y" && restartChoice != "n" && restartChoice != "y" && restartChoice != "n"){
System.out.println("That is not a valid input. Please try again. ");
restartChoice = input.nextLine();
}
在每个nextLine
语句后添加nextLine
语句以使用此换行符。
choice = input.nextInt();
input.nextLine();
==
运算符也会比较对象引用。使用String#equals
:
while (restartChoice.equals("y") || restartChoice.equals("Y")) {
要防范NullPointerException
,您可以先放置String
字面值。此外,equalsIgnoreCase
可用于提供更短的if
语句表达式:
while ("y".equalsIgnoreCase(restartChoice)) {
while
语句表达式需要进行此更改。
答案 1 :(得分:0)
使用String.equals(otherString)
字符串是对象,而不是基元。您目前正在比较字符串的地址。