如何结束程序,并阻止用户被提示?

时间:2015-10-05 14:43:47

标签: java netbeans

当用户输入小于或等于0的宽度时,程序应结束,不提示用户输入长度,或输出区域或周长。如何在不使用System.exit(0)的情况下执行此操作?!?

public static void main(String[] args) {
    Scanner k = new Scanner (System.in);
    System.out.print("Please Enter a Width: ");
    double width = k.nextDouble();
    System.out.print("Please Enter a Length: ");
    double length = k.nextDouble();
    double area = width * length; 
    System.out.println("The Area is: " + area);
    double perimeter = 2 * (width + length);
    System.out.println("The Perimeter is: " + perimeter);

    if (width <=0)
        System.out.println("The Width Must Be Greater Than 0");

    else if (length <=0)
        System.out.println("The Length Must Be Greater Than 0");

    if (width == length)
    System.out.println("The Shape is a Square"); 

    else if (width != length)
    System.out.println("The Shape is a Rectangle");     

3 个答案:

答案 0 :(得分:1)

您始终可以跳出return

的方法

在你的情况下:

...
System.out.print("Please Enter a Width: ");
double width = k.nextDouble();
if (width <= 0)
    return;
...

答案 1 :(得分:1)

更改条件语句,以便仅在宽度大于0时执行其余代码:

Scanner k = new Scanner (System.in);
System.out.print("Please Enter a Width: ");
double width = k.nextDouble();
if (width <=0)
{
    System.out.println("The Width Must Be Greater Than 0");
}
else 
{
    System.out.print("Please Enter a Length: ");
    double length = k.nextDouble();
    double area = width * length; 
    System.out.println("The Area is: " + area);
    double perimeter = 2 * (width + length);
    System.out.println("The Perimeter is: " + perimeter);
    if (length <=0)
        System.out.println("The Length Must Be Greater Than 0");
    if (width == length)
        System.out.println("The Shape is a Square"); 
    else if (width != length)
        System.out.println("The Shape is a Rectangle");
}

答案 2 :(得分:1)

如果width小于零,程序将退出,不会提示用户输入length。我已将该逻辑扩展到length提示符,这样如果length小于0,程序也会停止。

根据brso05'的逻辑,我提出了以下建议:

Scanner k = new Scanner (System.in);
System.out.print("Please Enter a Width: ");
double width = k.nextDouble();

if (width <=0){
    System.out.println("The Width Must Be Greater Than 0");
}
else{
    System.out.print("Please Enter a Length: ");
    double length = k.nextDouble();

    if (length <=0){
        System.out.println("The Length Must Be Greater Than 0");
    }
    else{
         double area = width * length; 
         System.out.println("The Area is: " + area);
         ...
    }
}