我正在做一个 do while 循环,它要求用户输入 ID,但在用户输入任何内容之前,它总是会在一个循环后显示错误消息
I'm doing a do while loop where it asks user to input ID,but it will always show the error message after one loop before user enters anything
我要用户输入菜单ID
do {
id = "";
System.out.print("Enter Menu ID : ");
id = sc.nextLine();
correctInput = false;
for (int i = 0; i < menu.length; i++){
if ((id.toUpperCase()).equals(menu[i].getMenuID()) {
correctInput = true;
//codes that comparing the user entered **ID** with **ID** in the array
//and get the quantity that user entered and calculate the total price
}
if (correctInput == false)
System.out.println("\nInvalid ID, please enter again!\n");
} while (correctInput == false);
//codes that ask user whether to add-on
当用户想重复下单时,总是会在用户输入任何内容之前显示错误信息
Add-on? (Y/N) : y
Enter Menu ID :
Invalid ID, please enter again!
Enter Menu ID :
我能知道我的代码有什么问题吗?
从您分享的 input/output 片段来看,id = sc.nextLine()
似乎没有在等待用户输入。如果您仍有输入排队,则可能会发生这种情况 - 例如,您使用 next()
读取 "Add-on? (Y/N)" 的 "Y" 但没有处理 "Y" 之后的换行符。您可以通过在 while
循环之前设置另一个 nextLine()
before 来处理它,而忽略结果:
// Get rid of the queued newline character - return value can be ignored
sc.nextLine();
// Start the loop for reading the id:
do {
// code...
我会做的是比较字符串值而不用担心区分大小写。
if (id.equalsIgnoreCase(menu[i].getMenuID())){
correctInput = true;
// your code
}
我要用户输入菜单ID
do {
id = "";
System.out.print("Enter Menu ID : ");
id = sc.nextLine();
correctInput = false;
for (int i = 0; i < menu.length; i++){
if ((id.toUpperCase()).equals(menu[i].getMenuID()) {
correctInput = true;
//codes that comparing the user entered **ID** with **ID** in the array
//and get the quantity that user entered and calculate the total price
}
if (correctInput == false)
System.out.println("\nInvalid ID, please enter again!\n");
} while (correctInput == false);
//codes that ask user whether to add-on
当用户想重复下单时,总是会在用户输入任何内容之前显示错误信息
Add-on? (Y/N) : y
Enter Menu ID :
Invalid ID, please enter again!
Enter Menu ID :
我能知道我的代码有什么问题吗?
从您分享的 input/output 片段来看,id = sc.nextLine()
似乎没有在等待用户输入。如果您仍有输入排队,则可能会发生这种情况 - 例如,您使用 next()
读取 "Add-on? (Y/N)" 的 "Y" 但没有处理 "Y" 之后的换行符。您可以通过在 while
循环之前设置另一个 nextLine()
before 来处理它,而忽略结果:
// Get rid of the queued newline character - return value can be ignored
sc.nextLine();
// Start the loop for reading the id:
do {
// code...
我会做的是比较字符串值而不用担心区分大小写。
if (id.equalsIgnoreCase(menu[i].getMenuID())){
correctInput = true;
// your code
}