【问题标题】:Using switch statements in a while loop在 while 循环中使用 switch 语句
【发布时间】:2024-01-21 21:30:01
【问题描述】:

我试图在 Java 的 while 循环中使用 switch 语句,但出现了问题。请查看下面解释我的问题的示例代码:

Scanner input=new Scanner(System.in);
    int selection = input.nextInt();

while (selection<4)
      {  switch(selection){
            case 1:
               System.out.println("Please enter amount");
               double amount=input.nextDouble(); //object of scanner class
               break;

            case 2:
               System.out.println("Enter ID number"); 
               break;

            case 3:
               System.out.println("Enter amount to be credited");
               break;
                          }
System.out.println("1. Transfer\n2.Check balance\n3.Recharge");
     }

如果我运行这段代码,输出如下:

1
Please enter amount
2000
1. Transfer
2.Check balance
3.Recharge
Please enter amount
2
1. Transfer
2.Check balance
3.Recharge
Please enter amount

当我输入金额时,我想选择另一个选项 - 输出应该根据所选择的选项(您可能应该知道我希望这段代码做什么)。有人可以帮忙更正代码吗?

谢谢

【问题讨论】:

  • 您提示输入值,然后不再提示。您只需在开始时提示输入的 SAME 值上循环。

标签: java while-loop switch-statement


【解决方案1】:

您目前在 while 循环之前一次获取和设置选择值,因此无法在循环内更改它。解决方案:从 while 循环的 inside 的 Scanner 对象中获取您的下一个选择值。要理解这一点,请从逻辑上思考问题,并确保在头脑中和纸上仔细检查您的代码,因为该问题不是真正的编程问题,而是基本逻辑问题。


关于:

有人可以帮忙更正代码吗?

出于多种原因,请不要要求我们这样做。

  1. 这不是家庭作业完成服务
  2. 当您通过编写代码来学习如何编码时,您要求他人为您更改代码是在伤害自己。
  3. 确实,这是一个基本的简单问题,您可以自行解决。请试一试,只有当尝试不起作用时,才向我们展示您的尝试。

【讨论】:

  • 1.作业的问题是创建一个完整的程序(比这更复杂,说真的),我做到了。 2. 我并不是要让任何人更改我的代码。我只是需要指导。这可能是我的语言。抱歉 3. 感谢您的帮助 :)
【解决方案2】:

您忘记再次要求选择。输入后不会改变。

Scanner input=new Scanner(System.in);
int selection = input.nextInt();

while (selection<4)
{
   switch(selection){
        case 1:
           System.out.println("Please enter amount");
           double amount=input.nextDouble(); //object of scanner class
           break;

        case 2:
           System.out.println("Enter ID number"); 
           break;

        case 3:
           System.out.println("Enter amount to be credited");
           break;
      }
      System.out.println("1. Transfer\n2.Check balance\n3.Recharge");
      selection = input.nextInt(); // add this
 }

您甚至可以使用 do...while 循环来避免两次写入 input.nextInt();

Scanner input=new Scanner(System.in);
int selection;

do
{
   selection = input.nextInt();
   switch(selection){
        case 1:
           System.out.println("Please enter amount");
           double amount=input.nextDouble(); //object of scanner class
           break;

        case 2:
           System.out.println("Enter ID number"); 
           break;

        case 3:
           System.out.println("Enter amount to be credited");
           break;
      }
      System.out.println("1. Transfer\n2.Check balance\n3.Recharge");
 }
 while(selection < 4);

【讨论】:

  • 傻我!感谢您解决这个问题
【解决方案3】:

case 必须大于 4,在你的情况下,case 小于 4。所以你不会退出循环,基本上 break 语句会中断 switch 并跳转到循环,但循环又小于 4所以它再次跳入开关等等。修正你的案例的大小,也许只是做一个

(selection != 1 || selection != 2 || selection !=3 || selection !=4)

【讨论】: