在while循环中使用switch语句 [英] Using switch statements in a while loop

查看:56
本文介绍了在while循环中使用switch语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to use switch statements in a while loop in Java, but there is something going wrong. Please have a look at a sample code below which explains my problem:

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

如果运行此代码,输出如下:

If I run this code, the output is as follows:

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

当我输入金额时,我想选择另一个选项-输出应根据所选择的选项(您可能应该知道我想要此代码执行的操作).有人可以帮忙更正代码吗?

When I enter the amount, I would then like to choose another option - and the output should be according to the option chosen (you should probably be knowing what I want this code to do). Could someone please help correct the code?

谢谢

推荐答案

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

You're forgetting to ask for the selection again. It's not going to change once it's been entered.

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

You could even use a do...while loop instead to avoid writing input.nextInt(); twice

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

这篇关于在while循环中使用switch语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆