我写了以下 Java 代码,想问一下,如果用户输入距离 <0,我如何继续询问用户正确的距离?我是否必须每次创建一个新变量,或者是否可以循环整个过程并获取Int,只有当距离>=0 时?非常感谢。
public class W05Practical {
public static void main(String [] args) {
System.out.println("Please enter the lengths/distance in meters:");
int Distance = EasyIn.getInt();
if (Distance >= 0) {
System.out.println("Thank you");
}
else {
System.out.println("Distance can not be negative. nPlease enter the appropriate distance:");
}
}
}
这是我对这个问题的建议。创建一个名为 correctInput 的布尔值,并让它监视它是否是正确的输入。
例如:
public class W05Practical {
public static void main(String[] args){
boolean correctInput = false;
while(!correctInput){
System.out.println("Please enter the lengths/distance in meters:");
int Distance = EasyIn.getInt();
if (Distance >= 0) {
System.out.println("Thank you");
correctInput = true;
}else {
System.out.println("Distance can not be negative. nPlease enter the appropriate distance:");
}
}
}
}