0

我编写了以下 Java 代码并想问如果用户输入 distance < 0 ,我如何继续询问用户正确的距离?我是否必须每次都创建一个新变量,或者只有在 Distance >=0 时才可以循环整个过程和 getInt?非常感谢。

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:");
    }   
}
}
4

1 回答 1

0

这是我对这个问题的建议。创建一个名为 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:");
            }  
        }    
    }
}
于 2013-10-13T00:40:30.430 回答