本文介绍了使用扫描仪的NoSuchElement的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
I have declared two strings and reading the input using Scanner(System.in).
之后,当我关闭Scanner并再次使用Scanner读取另一个输入时,它抛出错误: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);
}
}
推荐答案
当您close
扫描仪也关闭System.in
输入流时,您正在再次使用它,但它已关闭,因此当您再次尝试使用Scanner
时,找不到打开的System.in
流。
这篇关于使用扫描仪的NoSuchElement的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!