NoSuchElement使用扫描仪

时间:2014-12-30 07:52:07

标签: java java.util.scanner nosuchelementexception

I have declared two strings and reading the input using Scanner(System.in).

在此之后,当我关闭扫描仪并再次使用扫描仪读取另一个输入时,它会抛出错误: NoSuchElementException 。 请指导我这个

import java.util.Scanner;
import java.io.*;  

public class NumericInput

{
  public static void main(String[] args)
  {
    // Declarations
    Scanner in = new Scanner(System.in);
    String string1;
    String string2;

   // Prompts 
    System.out.println("Enter the value of the First String .");
   // Read in values  
    string1 = in.nextLine();
    // When i am commenting below line(in.close) code is working properly. 
    in.close();
    Scanner sc = new Scanner(System.in);
    System.out.println("Now enter another value.");
    string2 = sc.next();
    sc.close();

    System.out.println("Here is what you entered: ");
    System.out.println(string1 + " and " + string2);
  }

}

2 个答案:

答案 0 :(得分:4)

当您close扫描仪时它还会关闭System.in输入流,您再次使用它,但它已关闭,因此当您再次尝试使用Scanner时,不会打开{{找到1}}流。

答案 1 :(得分:0)

无需关闭扫描程序,因为它实现了 AutoCloseable 接口,您应该在java 7中的try-with-resources中声明资源。如果关闭Scanner是个问题。

try(Scanner in = new Scanner(System.in); Scanner sc = new Scanner(System.in)){
 // do stuff here without closing
}

 catch(Exception){
  e.printStackTrace();
 }