使用try catch块

时间:2016-01-27 19:56:19

标签: java io try-catch

运行此代码时出现问题。它执行第一个和第二个System.out.println就好了。程序然后调用IOHelper,它允许我输入一个数字。输入值后,将打印出#34;获取: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

1 个答案:

答案 0 :(得分:2)

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

要么抓住它,要么在读取令牌之前添加检查输入

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