gpt4 book ai didi

Java 在 "invalid input"上循环一个 switch-case 语句

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:23:18 25 4
gpt4 key购买 nike

如果用户输入任何未定义选项的内容,我希望更新我的代码以循环我的 swtich 语句。我在这里搜索了从各种搜索词返回的众多页面并且已经接近但到目前为止仍然没有运气。我这里的代码应该让任何想要试一试的人都能使用。

 java.util.Scanner;
//import java.lang.Character.*;
//Thought this was needed to grab single char but its not
public class caseloop {
//main Method
public static void main(String[] args)
{
Scanner input=new Scanner(System.in); //make so you can give input
boolean go = true; // for starting main outer loop
boolean run=true; // start inner loop
while (go==true)
{
while (run==true)
{
//Output
System.out.println("Enter option \n 1-Do this \n 2-Do this thing \n 3-Do this other thing");
int option= input.nextInt(); //grab option number

switch(option)
{
/*
* This needs to loop and prompt user again if anything other than 1,2, or 3 is entered.
*/
case 1:
System.out.println("Option1");
break;
case 2:
System.out.println("Option2");
break;
case 3:
System.out.println("Option3");
break;
/*case 4:
System.out.println("Option1");
System.out.println("Option2");
System.out.println("Option3");

break;
*
*
* Case 4 was for debug
*
*/
default:
System.err.println("Invalid option selected");
/*
* On input that is not defined with in the switch-case it will revert to "default"
* this fault staement needs to tell ther usere their option is not vaild and then
* prompt them to try it again to enter an option. I can not get it to reprompt.
* I have tried a while and an if loop both sorta worked but did not actually loop
* back to display again. I have been instucted that I am to not use a try catch statment
* unless of course that is the only viable option in whichcase I will use it anyways.
*/

//stupid default statement and its redundent built in "break;"

}
run=false;
}


/*
* Outer Loop to prompt user if they want to run the entire program again with new entries.
*/
if (run == false)
{
System.out.println("Would you like to run again? Y/N");
char again = input.next().charAt(0);
again = Character.toUpperCase(again); //force all leters inputed to upper case, lower would work too if i change if conditions
if (again == 'Y')
{
run = true;
}
else if (again == 'N')
{
System.out.println("Goodbye.");
go=false;
}
else
{
System.err.println("Invalid entry. Try again.");
}
}
}
}
//System.err.println("An error occured please try again");

}

如有任何帮助,我们将不胜感激。

最佳答案

您正在以一种非常奇怪的方式使用 run 变量。由于您在循环结束时将 run 设置为 false,因此循环将永远不会重复。如果您将其更改为仅设置有效选项 run=false,则输入错误的选项将导致循环再运行一次。

去掉switch语句末尾的run=false,添加在System.out.println("OptionX");之后>

关于Java 在 "invalid input"上循环一个 switch-case 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9410838/

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