gpt4 book ai didi

java - NoSuchElementException 问题

转载 作者:行者123 更新时间:2023-11-30 09:32:01 26 4
gpt4 key购买 nike

我想做的是创建一个 while 循环,在该循环中运行程序菜单,直到用户输入有效响应。

但是,我创建的扫描仪实例不想玩球,无论我尝试了什么,它都会继续抛出 NoSuchElementExceptions。

import java.util.Scanner;

public class Menu
{
Menu()
{
isValid = false;
uInput = 0;
}

public int mMain()
{
Scanner in2;

do
{
in2 = new Scanner(System.in); //For user input

System.out.println("Please choose from the following options");
System.out.println("1) Enter Employee Data");
System.out.println("2) Look Up Employee Information");
System.out.println("3) Employee Comparison");
System.out.println("4) Quit");
uInput = in2.nextInt(); //This is the line throwing the exception.

if (uInput < 1 || uInput > 4)
{
System.out.println("Your choice was not valid, please choose another option.");
}

else
{
isValid = true;
in2.close();
}
} while (!isValid);

isValid = false; //reset for next time
System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"); //Clear screen

return uInput;
}

int uInput; //For user input
String uInput2; //for bug fixing
boolean isValid; //check for valid use input
}

如果需要,这里是我的主要方法:

public class prg420_w4_commission_program
{
public static void main(String[] args)
{
//class references
Processing proc = new Processing();
Menu menu = new Menu();

//Set up Variables
int uInput; //For user input
boolean uQuit = false; //set up program loop bool

//Opening message
System.out.println("Welcome to the Employee Data Entry Creation program. Please follow the on-screen prompts.");
System.out.println("");

proc.initEDatabase(); //initialize employee database


while (!uQuit)
{

uInput = menu.mMain(); //call main menu

//Check user input
switch (uInput)
{
case 1:
proc.addEDBEntry(); //add employee entries
break;

case 2:
proc.findEmployee();
break;

case 3:
proc.sortEDBase();
break;

case 4:
uQuit = true;
break;

default:
proc.addEDBEntry();
break;
}
}

System.out.println("Thank you for using the Employee Data Entry Creation program.");
}
}

最佳答案

in2.close();

关闭输入流,在第一次成功扫描后,stdin 关闭,每次尝试使用 Scanner 从中获取任何内容都会导致 NoSuchElementException 被抛出。

关于java - NoSuchElementException 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12665591/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com