java - 禁止程序输入小于1的数字(if else/switch)

标签 java if-statement switch-statement conditional-statements

所以我正在编写一个比较盒子体积的程序...但我需要让它运行,以便不打印小于一的值并提示错误消息。 (即“第一个框是第二个框大小的 0.5 倍”或“第一个框是第二个框大小的 0 倍”)-- 相反,我希望它打印“错误:请输入大于的有效数字”大于 1"

这是我试图修复的代码部分:

if (volume1 == volume2) {
        System.out.println("The first box is the same size as the second box");
    }else if(volume1 >= 0 || volume2 >= 0){
        System.out.println("Error. Please enter a valid number greater than 0");
    }else {
        String bigger = "first box";
        String smaller = "second box";
        double ratio = volume1 / volume2;
        if (volume2 > volume1) {
            bigger = "second box";
            smaller = "first box";
            ratio = volume2 / volume1;
        }
        String compare;
        switch((int) ratio) {
        case 1: compare = " is slightly bigger than "; 
        break;
        case 2: compare = " is twice the size of "; 
        break;
        case 3: compare = " is triple the size of ";
        break;
        case 4: compare = " is quadruple the size of "; 
        break;
        default: compare = " is " + (int) ratio + " times the size of ";
        break;
        }

        System.out.println("The " + bigger + compare + smaller);
    }

我希望这是足够的代码来解释我的问题是什么。据我所知,我认为 switch 语句不能有条件,并且由于 int 比率的构造方式,当我测试它时,它会一直打印 0。有什么建议吗?

最佳答案

好的,我希望我正确回答了你的问题:) 那么你可以在默认分支中添加一点 if 语句:

// Here the Code till default
default:
    if (ratio < 1) {
        System.err.println("Error: Please enter a valid number greater than 1");
        return; // You should consider to return out of the method here otherwise "The" still gets printed for no reason :)
    } else compare = " is " + (int) ratio + " times the size of ";
}
// Rest of Code

这应该可以完成工作:)

关于java - 禁止程序输入小于1的数字(if else/switch),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53073497/

相关文章:

c - C 嵌入式软件中的查找表与开关

c++ - 替代 IF 语句和 switch case

java - 寻找 GSM/CDMA 通话详细记录结构

if-statement - 当我不关心 `if` 语句中包含什么值时,如何使用枚举?

c# - datagridview 事件的枚举索引

c# - 如何让控制台读取所有条件

c++ - 为什么 switch 和 if 语句与转换运算符的行为不同?

java - 带条件的 Hibernate 调用函数

java - 将某物与数据类型(如字符、字符串等)进行比较

java.lang.NullPointerException :at com. mysql.jdbc.ResultSet.buildIndexMapping