gpt4 book ai didi

java - 如果用户输入不正确,如何让问题循环

转载 作者:行者123 更新时间:2023-11-30 01:47:52 25 4
gpt4 key购买 nike

每当用户输入不正确的数据时,程序都会发出一条消息,告诉用户重试,但随后它会返回主菜单,而不是让用户尝试输入不同的值。我怎样才能做到这一点?

public void createStudentRecord(Scanner in)
{
inputStudentID = null;
inputMark = 0;

System.out.println("Enter Student ID: ");
in.nextLine();
inputStudentID = in.nextLine();
if (!(inputStudentID.length()==6))
{
System.out.println("Enter a student ID that is 6 characters");
}
else
{
System.out.println("Enter Module Mark: ");
inputMark = in.nextInt();
if (inputMark <0 || inputMark >100)
{
System.out.println("PLease enter a module mark between 0-100");
}
else
{
addStudent(inputStudentID, inputMark);
System.out.println();
System.out.println("New student record has been " +
"successfully created");
System.out.println();
countRecords();
}
}
}

最佳答案

一种方法是循环,直到看到正确/所需的输入。这种方法的一个问题是,如果用户没有输入预期值(如果这是您正在寻找的值),它永远不会终止,

代码片段:

public void createStudentRecord(Scanner in) {
String inputStudentID = null;
int inputMark = 0;

while (true) {
System.out.println("Enter Student ID: ");
inputStudentID = in.nextLine();
if (!(inputStudentID.length() == 6)) {
System.out.println("Enter a student ID that is 6 characters");
} else {
break;
}
}

while (true) {
System.out.println("Enter Module Mark: ");
inputMark = Integer.parseInt(in.nextLine());
if (inputMark < 0 || inputMark > 100) {
System.out.println("PLease enter a module mark between 0-100");
} else {
break;
}
}

addStudent(inputStudentID, inputMark);
System.out.println("\nNew student record has been successfully created.\n");
countRecords();
}

关于java - 如果用户输入不正确,如何让问题循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57280159/

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