Java 禁止程序输入小于1的数字(如果有/切换)
所以我正在写一个程序来比较盒子的体积。。。但我需要使其运行,以便不打印小于1的值,并提示错误消息。i、 e.第一个框的大小是第二个框的0.5倍,或者第一个框的大小是第二个框的0倍-我希望它打印错误:请输入大于1的有效数字 以下是我试图修复的代码部分:Java 禁止程序输入小于1的数字(如果有/切换),java,if-statement,switch-statement,conditional,Java,If Statement,Switch Statement,Conditional,所以我正在写一个程序来比较盒子的体积。。。但我需要使其运行,以便不打印小于1的值,并提示错误消息。i、 e.第一个框的大小是第二个框的0.5倍,或者第一个框的大小是第二个框的0倍-我希望它打印错误:请输入大于1的有效数字 以下是我试图修复的代码部分: if (volume1 == volume2) { System.out.println("The first box is the same size as the second box"); }else if(volum
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
这应该可以完成工作:如果卷1>=0 | |卷2>=0,则可能存在重复,这意味着您的打印错误。请在任意一个值大于0时输入一个大于0的有效数字。我想你指的是ifvolume1