3
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);
  }

}
4

2 回答 2

4

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

于 2014-12-30T07:54:17.757 回答
0

不需要关闭 Scanner,因为它实现了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();
 }
于 2014-12-30T08:13:19.953 回答