如何捕获NoSuchElementException? [英] how to catch a NoSuchElementException?

查看:379
本文介绍了如何捕获NoSuchElementException?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的类分配是写一个程序,用户输入一组数值。如果用户输入的数字不是数字,程序应该给予用户2次正确输入数字的机会,并且在这两次机会之后,退出询问输入并打印正确输入的所有值的总和。

My class assignment is to write a program that has the user input a set of numerical values. If the user enters a value that is not a number, the program is supposed to give the user 2 second chances to enter a number correctly, and after those two chances, quit asking for input and print the sum of all values entered correctly so far.

同样,我的代码工作不正确。当输入第一个非数字时,程序将执行catch块中的代码一次,在try块的开始处打印gimme input行,然后立即执行代码阻止再次阻止用户输入另一个数字。

As is, my code doesn't work quite right. When the first non-number is entered, the program executes the code in the catch block once, prints the "gimme input" line at the beginning of the try block but then immediately executes the code in the catch block again without waiting for the user to enter another number.

在阅读我的教科书的线索时,我注意到这一行:NoSuchElementException is not catch <强制>任何catch子句,异常仍然被抛出,直到被另一个try块捕获或主方法终止。

While perusing my textbook for clues, I noticed this line: "A NoSuchElementException is not caught by any of the catch clauses. The exception remains thrown until it is caught by another try block or the main method terminates."

哪个是伟大的,因为现在在至少我知道这是一个很好的理由,但我的教科书没有包含任何进一步的信息这个怪癖,我还没有找到任何可理解的答案通过StackOverflow或谷歌。所以我的问题是两部分:

Which is great, because now at least I know there's a good reason this is happening, but my textbook doesn't contain any further information on this quirk, and I haven't been able to find any understandable answers via StackOverflow or Google. So my question is two part:

a)为了这个任务的目的,我该如何解决这个问题?

a) How should I get around this for the purposes of this assignment?

b)究竟是什么意思,异常没有被catch子句捕获?是不是存在什么catch子句?我想要解决我的任务,但我也想了解为什么这是它的方式,如果可能的话。

b) What exactly does it mean that the exception is not caught by a catch clause? Isn't that what catch clauses exist for? I do want a solution to my assignment, but I also want to understand why this is the way it is, if possible.

感谢任何帮助!

import java.util.InputMismatchException;
import java.util.NoSuchElementException;
import java.util.ArrayList;
import java.util.Scanner;

public class NotANumber {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.println("This program computes the sum of any number of real numbers. When you are done entering values, enter something other than a real number twice in a row.\n");

        ArrayList<Double> numbers = new ArrayList<Double>();

        int count = 0;
        while (count < 2) {
            try {
                System.out.println("Please enter a floating point number: ");
                double newNumber = in.nextDouble();
                numbers.add(newNumber);
                count = 0;
            }
            catch (NoSuchElementException exception) {
                System.out.println("The value entered was not correctly specified. All values must be integers or floating point values.");
                count++;
            }
        }

        if (!numbers.isEmpty()) {
            double sum = 0;
            for (Double each : numbers) {
                sum = sum + each;
            }
            System.out.println("The sum is " + sum);
        }
        else {
            System.out.println("There is no sum as no correctly specified values were entered.");
        }

    }
}


推荐答案

现在,忘记捕捉异常(这不是你想要做的!)。您要做的是在调用s.nextDouble()之前添加如s.hasDouble()的调用。

For now, forget about catching the exception (it isn't what you want to do!). What you want to do is add calls like: s.hasDouble() before calling s.nextDouble().

您不想捕获该异常的原因是因为它是一个RuntimeException,它是用来表示一个程序员的错误,你应该修复一个。

The reason you don't want to catch that exception is because it is a RuntimeException which is meant to be used to indicate a programmer mistake, one that you should fix.

简单的建议是不会捕获编译器的异常不会告诉你抓住,而是如果其中一个被抛出,就可以弄清楚你需要对你的代码做出的改变,以免异常发生。

The simple advice is don't catch exceptions that the compiler doesn't tell you to catch, instead if one of them is thrown figure out the change you need to make to your code so that exception doesn't happen.

例外,编译器告诉你,你必须处理他们,你做的事情像:

For exceptions the compiler tells you that you must deal with them you do something like:

try
{
    foo();
}
catch(final IOException ex)
{
    // do something smarter here!
    ex.printStackTrace();
}

在该代码中,foo()被声明为:

In that code, foo() is declared something like:

public void foo() 
    throws IOException 
{
   // ... code ...
}

IOException是一个检查的异常(RuntimeException,也称为未检查异常,不应该被捕获,检查异常必须被捕获...你可以做其他事情超越捕获,但现在不要担心那些)。

IOException is a checked exception (RuntimeException, also called unchecked exceptions, should not be caught, checked exceptions must be caught... well you can do other things beyond catch, but for now don't worry about those).

所以,长回答短,在调用 s.nextXXX()之前调用 s.hasXXX()发生异常。

So, long answer short, make the exception not happen by calling s.hasXXX() before calling s.nextXXX().

这篇关于如何捕获NoSuchElementException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆