java.util.NoSuchElementException 没有这样的元素异常

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15109842/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 18:30:18  来源:igfitidea点击:

java.util.NoSuchElementException No Such Element Exception

java

提问by Ravin

New to Java - just trying to get a handle on it. The program is executing as follows:

Java 新手 - 只是想掌握它。程序执行如下:

What's your age?23
23
What's your name?Exception in thread "main" java.util.NoSuchElementException
    at java.util.Scanner.throwFor(Unknown Source)
    at java.util.Scanner.next(Unknown Source)
    at king.getName(king.java:25)
    at king.main(king.java:9)

The code it is trying to run is below:

它试图运行的代码如下:

import java.util.*;

public class king {



    public static void main(String[] args){
        System.out.println(getAge());
        System.out.println(getName());
    }

    public static int getAge(){
        System.out.print("What's your age?");
        Scanner scanner = new Scanner(System.in);
        String age = scanner.next();
        scanner.close();
        int numberAge = Integer.parseInt(age);
        return numberAge;

    }

    public static String getName(){
        System.out.print("What's your name?");
        Scanner newScanner = new Scanner(System.in);
        String name = newScanner.next();
        newScanner.close();
        return name;
    }

}

回答by Aniket Inge

Do not use scanner.close()<- source of your error!

不要使用scanner.close()<- 错误的来源!

remove the lines scanner.close()and newScanner.close()

删除线条scanner.close()newScanner.close()

From Java DOCs:

来自 Java 文档:

When a Scanner is closed, it will close its input source if the source implements the Closeable interface.

当 Scanner 关闭时,如果源实现 Closeable 接口,它将关闭其输入源。

Which means it closes the System.in- bad choice!

这意味着它关闭了System.in- 糟糕的选择!

From source code of Scanner.javain JDK, throwFor()is:

Scanner.javaJDK中的源代码来看,throwFor()是:

private void throwFor() {
    skipped = false;
    if ((sourceClosed) && (position == buf.limit()))
        throw new NoSuchElementException();
    else
        throw new InputMismatchException();
}

Clearly, if we have reached the end of input, OR if the source is closed, then we get the NoSuchElementException(). I am pretty sure the one at IDEONEhas happened because of position == buf.limit()rather than sourceClosed

显然,如果我们已经到达输入的末尾,或者如果源已经关闭,那么我们得到NoSuchElementException(). 我很确定IDEONE发生的那件事是因为position == buf.limit()而不是sourceClosed

回答by Christophe Roussy

Try this:

试试这个:

public class King {
  public static void main(final String[] args) {
    final Scanner scanner = new Scanner(System.in);
    System.out.println(getAge(scanner));
    System.out.println(getName(scanner));
  }

  public static int getAge(final Scanner scanner) {
    System.out.print("What's your age?");
    final String age = scanner.next();
    final int numberAge = Integer.parseInt(age);
    return numberAge;
  }

  public static String getName(final Scanner scanner) {
    System.out.print("What's your name?");
    final String name = scanner.next();
    return name;
  }
}

Also note that java classes should be capitalized.

还要注意java类应该大写。

回答by Bhushan

I think alraedy @Aniket has given a very good answer.

我认为 alraedy @Aniket 已经给出了很好的答案。

  • First of all instead of import java.util.*;you can use import java.util.Scanner;so it will not import unnecessary classes.
  • Second thing is that you can have a single Scannerlike i have shown in the example.(so you can close it)

     import java.util.Scanner;
     public class SO6 {
         static Scanner scanner = new Scanner(System.in);
         public static void main(String[] args){
             System.out.println(getAge());
             System.out.println(getName());
             scanner.close();
         }
    
        public static int getAge(){
            System.out.print("What's your age?");
            String age = scanner.next();
            int numberAge = Integer.parseInt(age);
            return numberAge;
    
        }
    
        public static String getName(){
            System.out.print("What's your name?");
            String name = scanner.next();
            return name;
        }
    }
    
  • 首先代替import java.util.*;你可以使用import java.util.Scanner;它不会导入不必要的类。
  • 第二件事是你可以Scanner像我在例子中展示的那样拥有一个。(所以你可以关闭它)

     import java.util.Scanner;
     public class SO6 {
         static Scanner scanner = new Scanner(System.in);
         public static void main(String[] args){
             System.out.println(getAge());
             System.out.println(getName());
             scanner.close();
         }
    
        public static int getAge(){
            System.out.print("What's your age?");
            String age = scanner.next();
            int numberAge = Integer.parseInt(age);
            return numberAge;
    
        }
    
        public static String getName(){
            System.out.print("What's your name?");
            String name = scanner.next();
            return name;
        }
    }
    

回答by Gunnarr

First of all, to avoid NoSuchElementException you should perform Scanner.hasNext() check before using Scanner.next(). Other comments especially about using single scanner are also useful.

首先,为了避免 NoSuchElementException,您应该在使用 Scanner.next() 之前执行 Scanner.hasNext() 检查。其他特别是关于使用单个扫描仪的评论也很有用。