gpt4 book ai didi

java - 使用 try catch block 时出错

转载 作者:行者123 更新时间:2023-11-30 03:04:49 26 4
gpt4 key购买 nike

运行此代码时遇到一些问题。它执行第一个和第二个 System.out.println 就很好。然后程序调用 IOHelper,它允许我输入一个数字。输入值后,它会打印“获得:xxxx”,然后打印“请输入风速:”,然后打印此错误列表。

Exception in thread "main" java.util.NoSuchElementException    
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextDouble(Unknown Source)
at Assignment1_14.IOHelper(Assignment1_14.java:49)
at Assignment1_14.main(Assignment1_14.java:27)

我正在使用 eclipse。

public class Assignment1_14 {

// declaring constants
final static double GRAVITY = 9.807;
final static double MASS_INITIAL = 0.008;
final static int LAUNCH_VEL = 22;
final static int DENSITY = 1900;
final static double BURN_RATE = 0.003;
final static int MIN_ANGLE = -15;
final static int MAX_ANGLE = 15;
final static int MIN_WIND = -22;
final static int MAX_WIND = 22;

public static void main(String[] args){
System.out.println("Hello, in order to launch the Roman Candle, please set \n"
+ "the launch angle and wind velocity. Note, the launch angle must be \n"
+ "between 15 degrees and -15 degrees.\n\n");

System.out.println("Please enter the launch angle: ");
double angle = IOHelper(MIN_ANGLE, MAX_ANGLE);
System.out.println("Obtained: " + angle);

System.out.println("Please enter the wind velocity: ");
27 double windVel = IOHelper(MIN_WIND, MAX_WIND);
System.out.println("Obtained: " + windVel);
} // end main method

public static double IOHelper (double low, double high) {
Scanner screen = new Scanner(System.in);
double num = 0;
boolean inputOK = false;
String dump = null;

while (!inputOK) {
try {
49 num = screen.nextDouble();
dump = screen.nextLine();

if (num < low || num > high) {
inputOK = false;
continue;
} // end if statement
inputOK = true;
} catch (InputMismatchException e) {
dump = screen.nextLine();
System.out.println("\"" + dump + "\" is not a legal double, "
+ "please try again!");
} // end try-catch block
} // end input loop
screen.close();
return num;
} // end IOHelper method

最佳答案

由于没有要读取的元素,因此引发 NoSuchElement 异常。 https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#next%28%29

要么捕获它,要么在读取 token 之前添加输入检查

while (!inputOK) {
try {
if(!screen.hasNext()) continue;
num = screen.nextDouble();
....

关于java - 使用 try catch block 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35046834/

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