1

我知道这段代码写得非常糟糕(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();
        }
    }
}

}

4

2 回答 2

0

使用 String.equals(otherString)

字符串是对象,而不是原语。您当前正在比较字符串的地址。

于 2013-06-23T18:46:33.257 回答
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在 for语句表达式中需要进行此更改。

于 2013-06-23T18:42:12.017 回答