在Java中如何在“无效输入”时循环执行switch-case语句

3

我希望更新我的代码,以便在用户输入任何未定义选项时循环我的switch语句。我已经搜遍了这里返回的众多页面,并且已经接近成功,但到目前为止还没有运气。

这里的代码应该能让任何想尝试的人开始。

 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");

}

如果您能提供任何帮助,我们将不胜感激。


经过在此处收到的所有建议后,我进行了进一步的测试,最终程序中我使用了两种方法放在另一个 while 循环中。感谢大家的帮助。:D - Spartan-196
4个回答

1
你可以在循环中添加一个标签。这样当你得到正确的选项时,就会退出循环。
loop: 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 loop;
 case 2:
   System.out.println("Option2");
   break loop;
 case 3:
   System.out.println("Option3");
   break loop;
 /*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");
   continue; //this causes control to go back to loop condition

}

1

"run=false"这部分不在正确的位置,无论答案(有效或无效)如何都会执行。

您应该将“run=false;”移动到每个有效的case语句内,例如:

case 1:
       System.out.println("Option1");
       run=false;
       break; 

顺便说一下:"while (run==true)" 是多余的,你可以写成 "while(run)"。

原始实现中有 while(run)。如果我可以点赞和/或有两个被接受的答案,那就好了。 - Spartan-196

1
问题在于在默认情况下执行语句后,它将布尔值“run”设置为false,因此退出循环。我们需要的是一种跳过这个步骤的方法:
run = false;

而不是直接进入循环条件。一种解决方案是在default下添加一个'continue'语句:

 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");
       continue; //this causes control to go back to loop condition

   }

由于它只需要进行最小代码更改,因此在小规模的实施中,如此继续操作非常好。但是,在有两个while循环、几个if循环并最终以else结束并引导到switch的较大环境中,它会太过重复到内部while循环的顶部,提示重新输入所有输入,而不仅仅是switch-case的输入,因此这并不是一个好的选择。 - Spartan-196

1

你正在以一种非常奇怪的方式使用run变量。由于你将run设置为false,循环将永远不会重复。如果你改变一下,只有在有效选项中设置run=false,输入错误选项将导致循环再运行一次。

switch语句的末尾删除run=false,并将其添加到System.out.println("OptionX");之后。


非常感谢您的快速回复。在线社区是非常有帮助的。 - Spartan-196

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接