【问题标题】:Where are the three run time errors? [closed]三个运行时错误在哪里? [关闭]
【发布时间】:2023-07-11 00:42:01
【问题描述】:

这是代码,运行时错误在哪里?我试图找到它,但我就是找不到,有没有其他人看到这些错误可能在代码中的什么位置?

public class HasErrors
{
    public static void main(String [] args)
    {
        int x = 0;
        int y = 0;
        Scanner in = new Scanner("System.in");
        x = in.readInt();
        System.out.print("Please enter another integer: ");
        x = in.readInt();
        System.out.println("The sum is " + x + y);
    }
}

【问题讨论】:

  • "System.in" 无法解析为整数。
  • x = in.readInt(); 两次,没有y = in.readInt(); 可能不是错误,但可能不是预期的结果。
  • 当您对运行时(或任何其他类型的)错误有疑问时,您应该发布它给您的错误消息,以及您正在使用的输入,它给您的输出,以及这与您的预期有何不同。
  • 另外,不能编译的代码不可能有任何运行时错误。
  • @David 这是 OP 甚至没有尝试通过编译器运行的“查找错误”作业。

标签: java time


【解决方案1】:

如果你用System.in 实例化一个新的Scanner,它不应该有引号:

Scanner in = new Scanner(System.in);

here

【讨论】:

  • 也许 OP 想使用Scanner 扫描String
【解决方案2】:

如果用户输入的不是数字,比如Hello World,那么readInt() 将抛出一个InputMismatchExceptionScanner 类也没有 readInt 函数。我想你的意思是把nextInt

【讨论】:

    【解决方案3】:

    除了已经提到的 readInt 错误,X 和 Y 将在 println 语句中连接而不是添加。这可以通过将 x + y 放在括号中来解决。

    【讨论】:

      最近更新 更多