用户EasyIn的复杂条件表达式。

时间:2013-10-13 00:35:03

标签: java boolean conditional user-input

我编写了以下Java代码,并想询问如果用户输入距离< 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:");
    }   
}
}

1 个答案:

答案 0 :(得分: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:");
            }  
        }    
    }
}