有没有办法循环菜单并选择新值?

时间:2019-02-15 02:42:50

标签: jgrasp

对于我的计算机科学课程,我正在制作一个计算器,用户输入两个数字并选择要对其进行处理(乘,加,乘)。对于选项d,我必须让用户输入两个新数字,这些数字应在随后的选择/计算中使用,换句话说,返回到开头并遍历选项,但要包含新数字。这是我到目前为止的代码,

public class Calculator
{
    public static void main (String [] args)
    {

        double x, y, result;
        char choice;

        x = Input.readDouble("Enter the first number: ");
        y = Input.readDouble("Enter the second number: ");

        String menu = "Choose what to do with " + x + " and " + y + ":\n";
        menu = menu + "a. Add them.\n";
        menu = menu + "b. Multiply them.\n";
        menu = menu + "c. Exponentiate them.\n";
        menu = menu + "d. Enter new numbers.\n";
        menu = menu + "e. QUIT.";

        boolean again = true;
        while (again)
        {

            choice = Input.readChar(menu);
            Output.showValue("You chose ", choice);

            switch (choice)
            {
                case 'a':
                    result = x + y;
                    Output.showMessage(x + " + " + y + " is " + result);
                    break;
                case 'b':
                    result = x * y;
                    Output.showMessage(x + " x " + y + " is " + result);
                    break;
                case 'c':
                    result = (Math.pow(x, y));
                    Output.showMessage(x + " ^ " + y + " is " + result);
                    break;
                case 'd': //user enters new numbers to go throught he list with new numbers
                    x = Input.readDouble("Enter the first number: ");
                    y = Input.readDouble("Enter the second number: ");
                    continue; //or should I use break again?
                case 'e':
                    Output.showMessage("Goodbye!");
                    again = false;
                    break;
                default:
                    Output.showMessage("ERROR: " + choice + " is not a valid choice.");
            } //end switch

        } //end while

    } //end method main

} //end class Calculator

0 个答案:

没有答案