因此,我正在编写一个比较包装箱体积的程序...但是我需要使其运行,以便不会打印小于1的值并提示错误消息。 (即“第一个框是第二个框的大小的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。有什么建议吗?
答案 0 :(得分:1)
好的,我希望您的问题正确无误:) 好吧,您可以将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
这应该可以完成:)