有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java在比较值时没有这样的元素异常?

我正在创建一个应用程序,提示用户输入3个数字,它将平均输入的数字。但当我到达那里时,它立刻引发了一个无趣的例外

    int i1,i2;
    int sum;
    double d1, d2, d3;//declares values input by the user
    double avg; //variable for calculating final result

    System.out.println("Hello out there. \n" //displays information to the user
            + "I will add two numbers for you. \n"
            + "Enter two whole numbers on a line:");

    Scanner keyboardInt = new Scanner(System.in); //Scans for keyboard input
    i1 = keyboardInt.nextInt();
    i2 = keyboardInt.nextInt();
    sum = (i1+i2);
    System.out.println("The sum of those 2 numbers is: \n" + sum + "\n" + 
    "Now enter 3 decimal numbers on a line:");
    keyboardInt.close();

    Scanner keyboardDouble = new Scanner(System.in); //Scans for keyboard input
    d1 = keyboardDouble.nextDouble();//-\ THIS LINE THROWS THE EXCEPTION. ID ASSUME THE OTHER WILL DO THE SAME
    d2 = keyboardDouble.nextDouble();//stores values entered by the user
    d3 = keyboardDouble.nextDouble();//-/
    avg = ((float) (d1+d2+d3)/3.0);//adds the sum of the values entered and calculates the average
    keyboardDouble.close();//closes scanner

    DecimalFormat df = new DecimalFormat("###,###,###.00");//formats the inputed number to 2 decimal places

    System.out.println("The average of those three numbers is:");//displays the average of the numbers
    System.out.println(df.format(avg));                         //entered by the user

这就是问题所在:

Scanner keyboardDouble = new Scanner(System.in); //Scans for keyboard input
d1 = keyboardDouble.nextDouble();//-\ THIS LINE THROWS THE EXCEPTION. ID ASSUME THE OTHER WILL DO THE SAME
d2 = keyboardDouble.nextDouble();//stores values entered by the user
d3 = keyboardDouble.nextDouble();//-/
avg = ((float) (d1+d2+d3)/3.0);//adds the sum of the values entered and calculates the average
keyboardDouble.close();//closes scanner     

共 (2) 个答案

  1. # 1 楼答案

    来自^{}的文档

    Closes this scanner. If this scanner has not yet been closed then if its underlying readable also implements the Closeable interface then the readable's close method will be invoked. If this scanner is already closed then invoking this method will have no effect.

    所以,当你做keyboardInt.close();时,它也关闭了System.in。因此,当您试图调用.nextDouble()时,扫描器没有任何东西可以解析成double(因为底层流已关闭,因此没有读取任何内容),因此NoSuchElementException

    要解决这个问题,可以使用一个Scanner来读取所有用户输入,并在完成后调用close()

  2. # 2 楼答案

    删除keyboardInt.close()语句。它关闭底层的InputStream,即System.in。所以,当你创建keyboardDouble时,它就不能再读了,因为System.in是关闭的

    所以,要解决这个问题,使用一台扫描仪,你可以同时使用两种用途:

    Scanner keyboard = new Scanner(System.in);
    ...
    i1 = keyboard.nextInt();
    i2 = keyboard.nextInt();
    ...
    d1 = keyboard.nextDouble();
    d2 = keyboard.nextDouble();
    d3 = keyboard.nextDouble();