java菜单程序切换大小写避免退出如果从菜单中选择了数字

标签 java input switch-statement

package com.company;
import java.util.*;
import java.lang.*;

public class Main {

    public static void main (String[] args) {

        System.out.println("Enter Any one number from following list to carry out Equation  ");
        System.out.println("1.Add ");
        System.out.println("2.Subtract ");
        System.out.println("3.Divide ");
        System.out.println("4.Multiply ");
        Scanner in=new Scanner(System.in);
        int read=in.nextInt();

        System.out.println("Enter 2 number for Equation ");
        double a=in.nextDouble();
        double b=in.nextDouble();
        double r;
        switch (read) {
            case 1 -> r = a + b;
            case 2 -> r = a - b;
            case 3 -> r = a / b;
            case 4 -> r = a * b;
            default -> {
                System.out.println("Error! Select from 1 to 4 ");
                return;
            }
        }
        System.out.println("Result of Equation is:  "+r);
    }

        }

如果我选择任何大于 4 的数字。 switch case 不退出并要求用户输入 2 次,并在输入数字后 switch case 退出。 如果我选择大于 4 的数字,我应该怎么做才能让 switch case 退出?

最佳答案

如果您希望跳过 ab 的输入,则执行顺序是错误的 尝试添加条件 if block

double a;
double b;
if( 0 < r && r < 5) {
  a = in.nextDouble();
  b = in.nextDouble();
}

关于java菜单程序切换大小写避免退出如果从菜单中选择了数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62180982/

相关文章:

java - 将普通中缀表达式转换为标记数组列表

javascript - 设置输入字段的值后防止页面重新加载

c# - 如何以编程方式触发 WinRT/C#/XAML 中的按键事件?

c# - 什么是大型开关盒的良好替代品?

java - 做while循环错误(switch语句)

java - 让 Jackson 对输入 JSON 更友好

java - 在 void 方法上使用 @NonNull 有什么作用?

python - 如何在python中读取格式化输入?

java - 在 Java 中实现类似可扩展枚举的东西

java - Node java : Install error: "fatal error LNK1181 cannot open input file DelayImp.lib"