java.util.NoSuchElementException错误(可能是由于扫描仪引起的)

时间:2019-04-08 07:04:08

标签: java compiler-errors

我在尝试获取用户输入的行中收到“运行时错误” java.util.NoSuchElementException。不知道如何摆脱它。

public static void main (String[] args)
    {
        Scanner sc = new Scanner(System.in);
        int input = sc.nextInt();
        double amount = sc.nextDouble();
        if(input%5!=0){
            System.out.println(String.format("%.2f", amount));
        }else if(input>amount){
            System.out.println(String.format("%.2f", amount));
        }else{
            double bankAmount = 0.50;
            double ans = amount - (double)input;
            System.out.println(String.format("%.2f",ans-bankAmount));
        }
        sc.close();
    }

完整的错误是:

Exception in thread "main" java.util.NoSuchElementException
    at java.util.Scanner.throwFor(Scanner.java:862)
    at java.util.Scanner.next(Scanner.java:1485)
    at java.util.Scanner.nextInt(Scanner.java:2117)
    at java.util.Scanner.nextInt(Scanner.java:2076)
    at Codechef.main(Main.java:14)

1 个答案:

答案 0 :(得分:1)

 public static void main (String[] args)
    {        Scanner sc = new Scanner(System.in);
            System.out.println("Please enter an integer value:");
            if(sc.hasNextInt()) {
                int input = sc.nextInt();
                System.out.println("Please enter double value:");
                if(sc.hasNextDouble()) {
                    double amount = sc.nextDouble();
                    if(input%5!=0 ||input>amount){
                        System.out.println("amount="+String.format("%.2f", amount));
                    }else{
                        double bankAmount = 0.50;
                        double ans = amount - (double)input;
                        System.out.println("ans="+String.format("%.2f",ans-bankAmount));
                    }
                }            
        }     
       System.out.println("Program exited on invalid value!");
        sc.close();
    }