我有一个阅读用户输入的功能。它需要一个参数来选择读取Ints或Strings。当我试图确保它只读取Ints with while(!sc.hasNextInt())时它可以工作,但只有当我在调试模式下执行它时。每当我在程序运行时尝试使用它时,无论输入是数字还是字符,它都会抛出异常。
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at Databaz.ctecka(Databaz.java:14)
at Databaz.main(Databaz.java:38)
这指向sc.next();我的职能部分:
static String ctecka(int volba)
{
Scanner sc = new Scanner(System.in);
String vystup = "vystup";
if(volba == 1)
{
int cislo = 0;
while(!sc.hasNextInt())
sc.next(); //this is where exception points
cislo = sc.nextInt();
vystup = Integer.toString(cislo);
}
if(volba == 2)
{
vystup = sc.nextLine();
}
sc.close();
return vystup;
}
函数正在使用代码:
int volba = Integer.parseInt(ctecka(1)); //it returns String so i parse it
答案 0 :(得分:0)
之所以会发生这种情况,是因为您关闭扫描程序sc.close();
会关闭inputStream,然后再次尝试访问它(have a look here),以解决您的问题,概括您的扫描程序变量,然后仅关闭它完成所有ctecka()
方法调用后,如下所示:
Scanner sc;
private void some_method(){
int volba1 = Integer.parseInt(ctecka(1));
int volba2 = Integer.parseInt(ctecka(1));
int volba3 = Integer.parseInt(ctecka(2));
int volba4 = Integer.parseInt(ctecka(3));
sc.close();
}
String ctecka(int volba){
sc = new Scanner(System.in);
String vystup = "vystup";
if(volba == 1)
{
int cislo = 0;
while(!sc.hasNextInt())
sc.next();
cislo = sc.nextInt();
vystup = Integer.toString(cislo);
}
if(volba == 2)
{
vystup = sc.nextLine();
}
return vystup;
}