【发布时间】:2013-06-20 06:49:31
【问题描述】:
我知道这段代码写得非常糟糕(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();
}
}
}
}
【问题讨论】:
-
@原帖者,对于初学者来说,你的代码一点也不差,除了Reimeus指出的错误,我不同意这个说法:
"I know this code is terribly written (first day of Java and programming)..."跨度> -
@project_legacy 另外,请注意第一个
Scanner#readLine()呼叫 - 检查文档,但我认为restartChoice将是空的,所以这就是您看到That is not a valid input...的原因。 -
抱歉,假设您修复了字符串相等问题。
-
请注意,即使您修复了已经指出的错误,此代码也无法生成随机滚动,因为您在循环内创建了 Random 对象。将
new Random()移动到main()的开头,只调用一次,然后在循环中使用nextInt()。
标签: java loops random while-loop numbers