繁体   English   中英

switch 语句未正确执行

[英]switch statement not executing properly

我正在为 class 分配任务,所以我不能发布我的确切代码,但我可以举一个类似的例子。 我正在尝试建立一个银行系统,首先会显示一个菜单,让用户选择他们想做的事情。 我的问题是,当用户输入数字时,方法不会执行并且菜单会再次打印出来。

示例代码:

while(choose != 4){
System.out.println("Please choose from the following options");
System.out.println("1. Do this");
System.out.println("2. Do this!");
System.out.println("3. Do THIS!");
System.out.println("4. Close application")

Scanner scanny = new Scanner(System.in);
choose = scanny.nextInt();
switch(choose)
{  
   case 1:
        method1();
        break;
   case 2:
        method2();
        break;
   case 3:
        method3();
        break;
   case 4:
        System.out.close();
        break();
   default:
        return;
}
}
Output:

Please choose from the following options:
1. Do this
2. Do this!
3. Do THIS!
4. Close application

(User enters 2)

2
Please choose from the following options:
1. Do this
2. Do this!
3. Do THIS!
4. Close application

我希望这是有道理的..任何帮助表示赞赏,我很乐意清除任何东西!

我对您所做的进行了一些更改,下面的程序应该为您提供所需开关的模板。 最大的变化是将扫描仪创建拉到循环之外,因此它不会不断重新初始化。 我还注意到你的案例 4 没有 break() 。 我为这些方法编写了伪代码。 随意添加您自己的方法调用,但也请先保留我的方法以进行调试。 这是一个工作版本。

int choose = 0;
Scanner scanny = new Scanner(System.in);
while (choose != 4) {
    System.out.println("Please choose from the following options");
    System.out.println("1. Do this");
    System.out.println("2. Do this!");
    System.out.println("3. Do THIS!");
    System.out.println("4. Close application");


    choose = scanny.nextInt();
    switch (choose) {
        case 1:
            System.out.println("method 1");
            break;
        case 2:
            System.out.println("method 2");
            break;
        case 3:
            System.out.println("method 3");
            break;
        case 4:
            System.out.close();
            break;
        default:
            return;
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM