gpt4 book ai didi

java - 阅读双倍后扫描仪无法正常工作

转载 作者:行者123 更新时间:2023-11-29 05:03:50 25 4
gpt4 key购买 nike

<分区>

扫描器在调用 nextDouble() 后不等待输入,但在 nextLine() 后它工作正常。

import java.util.*;

public class calc {
public static final Scanner input = new Scanner(System.in);
public static void main(String[] args) {
while(true) {
calculate();
System.out.print("Would you like to run again? Y/N: ");
String repeat = input.nextLine().toLowerCase();
if (!(repeat.equals("y") || repeat.equals("yes"))) {
System.out.println("\nBye!\n");
break;
}
}
}
public static void calculate() {
System.out.print("\nAdd, Subtract, Multiply, Divide or Modulus? : ");
double fsnum, scnum, ans;
String choice = input.nextLine().toLowerCase();
if(choice.equals("add") || choice.equals("subtract") || choice.equals("multiply") || choice.equals("divide") || choice.equals("modulus")) {
System.out.print("Enter the first number: ");
fsnum = input.nextDouble();
System.out.print("Enter the second number: ");
scnum = input.nextDouble();
switch(choice) {
case "add":
ans = fsnum+scnum;
break;
case "subtract":
ans = fsnum-scnum;
break;
case "multiply":
ans = fsnum*scnum;
break;
case "divide":
ans = fsnum/scnum;
break;
case "modulus":
ans = fsnum%scnum;
break;
default:
ans = 0;
break;
}
System.out.println("The answer is: " + ans);
} else {
System.out.println("ERROR: Please select a valid operation.");
}
}
}

输出

Add, Subtract, Multiply, Divide or Modulus? : add
Enter the first number: 3
Enter the second number: 4
The answer is: 7.0
Would you like to run again? Y/N:
Bye!

如您所见,再次运行的最后一个输入被跳过,程序似乎将其假定为“”或 null。
如果选择了无效操作,这似乎不会发生。 -

Add, Subtract, Multiply, Divide or Modulus? : yaya
ERROR: Please select a valid operation.
Would you like to run again? Y/N: n

Bye!

有什么解决办法吗?

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