无限循环无法在Switch语句中关闭循环

时间:2018-02-28 06:48:26

标签: java loops do-while

import java.util.Scanner;

class MenuFastFood {

    public static void main(String[] args) {

        String s;
        char order;

        Scanner keyboard = new Scanner(System.in);

        s = keyboard.next();
        s = s.toUpperCase();
        order = s.charAt(0);

        do {
        switch(order) { 
            case 'A': 
                System.out.println("CheeseBurger");
                System.out.println("Onion Rings");
                System.out.println("Soda");
                break;

            case 'B':
                System.out.println("Hot dog");
                System.out.println("Fries");
                System.out.println("Milk Shake");
                break;

            default: 
                System.out.println("error");
                return;     

            case 'X':
                System.out.println("EXIT"); 
                break;          
            }
        }while(order != 'X');
    }

我的程序假设根据输入keybaord的字符选择一个项目,然后如果选择了另一个项目则循环返回。当我运行这个并选择一个项目。它永远地循环该项目。如何让它停下来让我能够选择另一个项目?

1 个答案:

答案 0 :(得分:0)

将用于读取输入的代码移动到内部do..while

        s = keyboard.next();
        s = s.toUpperCase();
        order = s.charAt(0);