循环切换代码不重复但执行其他情况

Loop switch code doesn't repeat but executes other case

我有一个 switch case 代码,显示有四个选项的菜单。选择和操作完成后,它会再次显示菜单。菜单中的最后一种情况(第四种选择)是退出。在我到达案例 3 的结尾之前,代码可以完美运行,但随后它不会再次显示菜单,而是直接跳转到执行案例 4 并终止程序。

(仅供参考,我对此很陌生,所以感谢您的耐心等待)。

代码如下:

do
{
   // Display the menu
   displayMenu();

   // Ask the user for one option
   System.out.println("Enter a number: ");

   switch (scan.nextInt()) 
   {
       // Define four cases for different options. Don't forget "break".
   case 1:
       System.out.print("Enter a number: ");
       sumInput = scan.nextInt();
       while (sumStart <= sumInput)
       {
           sumResult += sumStart;
           sumStart++;
       }
       System.out.println("The sum of 1 to " + sumInput + " is: " + sumResult);
       break;
   
   case 2:
       System.out.print("Enter a number: ");
       facInput = scan.nextLong();
       while(facStart <= facInput)
       {            
           facResult = facResult*facStart;
           facStart++;
       }         
       System.out.printf("%s %.0f %s %.0f %n", "The factorial of ",  facInput , " is ",  facResult);
       break;
                        
   case 3:
       System.out.print("Enter a number: ");
       int left = scan.nextInt();
       while(left >= 1)
       {               
           String leftString = String.valueOf(left);
       System.out.print("The leftmost digit of " + left + " is ");
       System.out.println(leftString.charAt(0));
       break;
       }

   case 4:
       System.out.print("Bye");
       System.exit(0);
   }
}
while (option < 4);

我认为在案例 3 中你在 while 循环中给出了 break 语句 尝试从 while 循环中删除 break 并在循环之后添加它

case 3:
               System.out.print("Enter a number: ");
               int left = scan.nextInt();
               while(left >= 1)
               {               
                   String leftString = String.valueOf(left);
               System.out.print("The leftmost digit of " + left + " is ");
               System.out.println(leftString.charAt(0));
               };break;

您想从 while 循环中取出 break 语句,这样它就不会立即中断:

case 3:
     System.out.print("Enter a number: ");
     int left = scan.nextInt();
     while(left >= 1)
     {               
          String leftString = String.valueOf(left);
          System.out.print("The leftmost digit of " + left + " is ");
          System.out.println(leftString.charAt(0));
     }
     break;