Java Зацикливание оператора switch-case на «неверном вводе» - PullRequest
3 голосов
/ 23 февраля 2012

Я хочу обновить свой код, чтобы зациклить мой оператор 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");

}

Любая помощь в этом будет очень признательна.

Ответы [ 4 ]

1 голос
/ 14 апреля 2016

Вы можете добавить метку в ваш цикл.Таким образом, когда вы получите правильный вариант, вы выйдете из цикла.

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 голос
/ 23 февраля 2012

Часть "run = false" не в нужном месте, она выполняется независимо от ответа (действительный или нет).

Вы должны переместить "run = false;"внутри каждого действительного оператора case, например:

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

Кстати, «while (run == true)» избыточно, вы можете написать «while (run)»

1 голос
/ 23 февраля 2012

Проблема в том, что после выполнения оператора по умолчанию он устанавливает логическое выполнение в false и, таким образом, выходит из цикла Нам нужен способ пропустить это: -

run = false;

и вместо этого перейдите непосредственно к условию цикла. Одним из решений было бы добавить оператор продолжения по умолчанию: -

 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

   }
1 голос
/ 23 февраля 2012

Вы используете переменную run очень странным образом. Поскольку вы устанавливаете прогон на false в конце цикла, цикл никогда не повторится. Если вы измените его так, чтобы только действительные параметры устанавливали run=false, то при вводе неправильного параметра цикл будет запущен еще раз.

Удалить run=false в конце оператора switch, добавить его после System.out.println("OptionX");

...