扫描器和循环的java问题
我一直在阅读有关Scanner的问题,但即使在添加了额外的in.nextLine()
或in.nextInt()
之后,Java所做的就是将NoSuchElementException
移到该行。有什么建议吗?我正在尝试为我的程序创建一个自动循环菜单选项。每次循环案例1时,它都有一个问题
while (!done) {
System.out.println("Welcome, please type a number for selecting from the following: \n 1. Insert Process \n 2. Print out a list of processes \n 3. See and remove first priority process \n 4. Quit");
Scanner in = new Scanner(System.in);
int selector = 0;
print(); in .nextLine();
selector = in .nextInt();
switch (selector) {
case 1:
System.out.println("Please enter a priority for the new process > 0");
Scanner pin = new Scanner(System.in);
priority = pin.nextInt();
if (priority > 0) {
maxHeapInsert(priority); //allows user to set priority
in .close(); in = new Scanner(System.in);
break;
} else {
System.out.println("ERROR, you did not enter a number greater than 0");
}
break;
}
}
# 1 楼答案
请尝试以下代码:
原因是当您使用
in.close()
时,它也将关闭System.in
,因此您将读取-1并抛出异常。请记住,程序在关闭System.in
后无法重新打开它# 2 楼答案
在尝试使用next*获取令牌之前,请使用scanner的hasNextLine及其其他变体
没有必要对
System.in
使用多个扫描仪# 3 楼答案
试试下面的代码
请注意,不需要使用/声明多个扫描仪。还应尽量避免在循环内声明变量,因为这样做效率不高(内存/性能)