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);
}
}
答案 0 :(得分:4)
答案 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();
}