gpt4 book ai didi

java - 我有一个关于 java 中使用 next.Line 的扫描器代码的问题。它适用于我的代码之一,但不适用于另一代码

转载 作者:行者123 更新时间:2023-12-02 01:15:32 26 4
gpt4 key购买 nike

我试图创建一个计算器,提示用户输入第一个数字,然后输入字符串运算符,最后提示用户输入第二个数字。当我输入完第一个提示的值时,最后一个提示与运算符(operator)提示一起出现,当我输入运算符(operator)时,会导致错误。

System.out.print("Enter the your first number: ");
double x = calculator.nextDouble();
System.out.print("Enter the operator: ");
String y = calculator.nextLine();
System.out.print("Enter the your second number: ");
double z = calculator.nextDouble();

这是我运行程序时得到的结果:

Enter the your first number: 5
Enter the operator: Enter the your second number: +
Exception in thread "main" java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Scanner.java:939)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextDouble(Scanner.java:2564)
at
Flow_Of_Control.Calculator_4_function_sc_statement.main(Calculator_4_function_sc_statement.java:37)

当我使用“.next()”时它工作正常,但我想知道为什么它不能与 .nextLine() 一起工作,因为下面的代码与 .nextline() 一起工作正常,而上面的代码没有。

    System.out.print("Enter your name: ");
String name = keyboardInput.nextLine();
System.out.print("Enter your Age: ");
int age = keyboardInput.nextInt();

最佳答案

nextDouble() 不会从控制台读取换行符,而是由 calculator.nextLine(); 读取。您可以在输出中看到它

Enter the operator: Enter the your second number: +

您将运算符插入到输入您的第二个数字:请求中,因此它由nextDouble()读取。

解决方法是在调用 nextDouble() 后调用 nextLine()

System.out.print("Enter the your first number: ");
double x = calculator.nextDouble();
calculator.nextLine();
System.out.print("Enter the operator: ");
String y = calculator.nextLine();

您也可以随时使用 nextLine() 并将其转换为正确的类型

System.out.print("Enter the your first number: ");
double x = Double.parseDouble(calculator.nextLine());

关于java - 我有一个关于 java 中使用 next.Line 的扫描器代码的问题。它适用于我的代码之一,但不适用于另一代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58678308/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com