【问题标题】:Why won't my Java code work? [duplicate]为什么我的 Java 代码不起作用? [复制]
【发布时间】: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


【解决方案1】:

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 语句表达式需要此更改。

【讨论】:

  • 谢谢你的回答,但我还是很困惑。即使在将字符串作为对象进行比较之后,它仍然会打印出输入不正确(重启选择不是“Y”或“N”,即使尚未输入任何内容。
  • 这是由于Scanner#nextInt 没有使用换行符。查看更新
  • 非常感谢,我的程序现在可以运行了。非常感谢您的帮助:)
【解决方案2】:

使用 String.equals(otherString)

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-09-26
    • 2021-10-28
    • 2015-09-09
    • 1970-01-01
    • 2020-06-07
    • 2013-05-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多