0

我遇到了 try & catch 的问题。要求是它必须在 do while 循环内。它必须捕捉非数值(为简单起见,我试图捕捉非双精度值)。输入数字时程序运行良好,但是当我输入字母时,它不会显示所需的“无数字”消息。代码如下:

    import java.util.*;
    import java.io.*;

    public class Triangle {

        public static void main(String[] args) throws NumberFormatException
        {

            // inputting a new scanner
            Scanner input = new Scanner(System.in);
            double a=0; double b=0; double c=0;
            do {   
                try{
                    // prompt the user to enter values
                    System.out.println("Enter values for triangle sides a, b and c"
                    + "\n(only numbers are accepted): ");
                    a=input.nextDouble(); // inputing and declaring value as double
                    b=input.nextDouble(); // inputing and declaring value as double
                    c=input.nextDouble(); // inputing and declaring value as double
                }
                catch (NumberFormatException nfe) {
                    System.out.println("Not a number");
                    }

                if (a == (double)a && b == (double)b && c == (double)c)
                    System.out.println("\nThe values you have entered are:\na = " + a +
                    "\nb = " + b + "\nc = " + c);

                boolean sumGreater = isTriangle(a, b, c); // invoking method isTriangle

                // if statement to check if entered values form triangle or not
                if (!sumGreater)

                    // Display message if statement is false
                    System.out.println("The entered values do not form a triangle");

                else
                    // Display output if message is true.
                    // Methods triangleType,
                    // perimeter and area, are invoked inside the output.
                    System.out.printf("\nThe type of triangle is: %s" + "\nPerimeter = %.2f" + "\nArea = %.2f \n", triangleType(a,b,c), perimeter(a,b,c), area(a,b,c));

            } while (a==(double)a && b==(double)b && c==(double)c);
        }

        // Defining method isTriangle as boolean
        public static boolean isTriangle(double a, double b, double c) {
            boolean sumGreater; // declaring expression as a boolean

            // if statement to check if the entered values form a triangle,
            // using the triangle inequality theorem, where sum of any two sides
            // must be greater the the remaining third side
            if((a+b)>c && (a+c)>b && (b+c)>a)
                sumGreater = true;
            else
                sumGreater = false;
            return sumGreater; // returning the value to main method
        }

        // Defining method perimeter as double
        public static double perimeter(double a, double b, double c) {
            double perimeter = a+b+c; // declaring the sum of the values as double
            return perimeter; // returning the value of perimeter to main method
        }

        // Defining method area as double, using Heron's formula to calculate area
        public static double area(double a, double b, double c) {
            double s=(a+b+c)/2;
            double h=s*(s-a)*(s-b)*(s-c);
            double area = Math.sqrt(h);
            return area; // returnig the value of area to main method
        }

        // Defining method triangleType as String, to determine type of triangle
        public static String triangleType(double a, double b, double c) {
            String triangleType = " ";

            // if statement to determine type of triangle
            if (a==b&&a==c&&b==c)
                triangleType = "Equilateral";
            else if(a==b||b==c||a==c)
                triangleType = "Isosceles";
            else
                triangleType = "Scalene";
            return triangleType; // returning value of triangleType to main method
        }
    }
4

5 回答 5

0

感谢大家的建议,终于设法编写了根据输入为我提供所需结果的代码:

    import java.util.*;
import java.io.*;

public class Triangle {

public static void main(String[] args) throws IOException
{

    // inputting a new scanner
    Scanner input = new Scanner(System.in);

    double a=0; double b=0; double c=0; // declaring and initializing doubles

    // starting do-while loop
    do {

        // using try-catch method to catch mistakenly entered values
        try{
            // prompt the user to enter values
            System.out.println("Enter values for triangle sides a, b and c"
            + "\n(only numbers are accepted): ");
            a=input.nextDouble(); // inputing and declaring value as double
            b=input.nextDouble(); // inputing and declaring value as double
            c=input.nextDouble(); // inputing and declaring value as double
        }
        catch (InputMismatchException e) {

            // display message if entered value isn't a number
            System.out.println("Not a number");
            }
    } while (a!=(double)a && b!=(double)b && c!=(double)c); // end of do-while loop

        // displaying entered values, while avoiding to display the initialized 
        if (a!=0 && b!=0 && c!=0)
            System.out.println("\nThe values you have entered are:\na = " + a +
                    "\nb = " + b + "\nc = " + c);

        boolean sumGreater = isTriangle(a, b, c); // invoking method isTriangle

        // if statement to check if entered values form triangle or not,
        // while avoiding the initialized values to be displayed
        if (!sumGreater && a!=0 && b!=0 && c!=0)

            // Display message if statement is false
            System.out.println("The entered values do not form a triangle");

        else if(a!=0 && b!=0 && c!=0)
            // Display output if message is true.
            // Methods triangleType,
            // perimeter and area, are invoked inside the output.
            System.out.printf("\nThe type of triangle is: %s" + 
                    "\nPerimeter = %.2f" + "\nArea = %.2f \n", 
                    triangleType(a,b,c), perimeter(a,b,c), area(a,b,c));
}

// Defining method isTriangle as boolean
public static boolean isTriangle(double a, double b, double c) {
    boolean sumGreater; // declaring expression as a boolean

    // if statement to check if the entered values form a triangle,
    // using the triangle inequality theorem, where sum of any two sides
    // must be greater the the remaining third side
    if((a+b)>c && (a+c)>b && (b+c)>a)
        sumGreater = true;
    else
        sumGreater = false;
    return sumGreater; // returning the value to main method
}

// Defining method perimeter as double
public static double perimeter(double a, double b, double c) {
    double perimeter = a+b+c; // declaring the sum of the values as double
    return perimeter; // returning the value of perimeter to main method
}

// Defining method area as double, using Heron's formula to calculate area
public static double area(double a, double b, double c) {
    double s=(a+b+c)/2;
    double h=s*(s-a)*(s-b)*(s-c);
    double area = Math.sqrt(h);
    return area; // returnig the value of area to main method
}

// Defining method triangleType as String, to determine type of triangle
public static String triangleType(double a, double b, double c) {
    String triangleType = " ";

    // if statement to determine type of triangle depending on met conditions
    if (a==b&&a==c&&b==c)
        triangleType = "Equilateral";
    else if(a==b||b==c||a==c)
        triangleType = "Isosceles";
    else
        triangleType = "Scalene";
    return triangleType; // returning value of triangleType to main method
}

}

于 2013-10-28T11:38:57.057 回答
0

行后有语法错误

} while (a==(double)a && b==(double)b && c==(double)c);

}在这一行之后放一个。你的程序似乎为我运行。

于 2013-10-27T18:26:42.543 回答
0

您正在尝试isTriangle()在另一个方法 ( ) 中定义一个方法 ( main())。你不能在 Java 中做到这一点。所有方法都必须在类内。

此外,如果 a、b 和 c 不是有效的双打,则不应尝试使用它们。所以,而不是做

try {
    // prompt the user to enter values
    System.out.println("Enter values for triangle sides a, b and c"
                 + "\n(only numbers are accepted): ");
    a=input.nextDouble(); // inputing and declaring value as double
    b=input.nextDouble(); // inputing and declaring value as double
    c=input.nextDouble(); // inputing and declaring value as double
}
catch (NumberFormatException nfe) {
    System.out.println("Not a number");
}

// use a, b and c, although they were not entered correctly

你应该做

try {
    // prompt the user to enter values
    System.out.println("Enter values for triangle sides a, b and c"
                + "\n(only numbers are accepted): ");
    a=input.nextDouble(); // inputing and declaring value as double
    b=input.nextDouble(); // inputing and declaring value as double
    c=input.nextDouble(); // inputing and declaring value as double

    // use a, b and c: you're sure they have been entered correctly
}
catch (NumberFormatException nfe) {
    System.out.println("Not a number");
}
于 2013-10-27T18:29:54.133 回答
0

您正在捕获错误类型的异常,并且您收到的错误消息会告诉您这一点。当令牌(在这种情况下 - 您输入的文本)不是浮点数时,该Scanner.nextDouble()方法会抛出。是由方法引发的,而不是由 Scanner引发InputMismatchException的。NumberFormatExceptionDouble.parseDouble()

作为一般建议,您应该阅读您使用的方法的 Javadoc 文档,因为它清楚地解释了调用它时可能遇到的结果类型和异常。编译器并不总是强制捕获异常,就像在这种情况下一样 -java.util.InputMismatchException是 a RuntimeException,即不是已检查的异常,因此不必捕获它。

于 2013-10-27T21:18:58.507 回答
0

请使用以下代码,它适合您的要求。后面有 } 缺失,请补充。

            try{
                // prompt the user to enter values
                System.out.println("Enter values for triangle sides a, b and c"
                + "\n(only numbers are accepted): \t");
                a=Double.parseDouble(input.next());
                b=Double.parseDouble(input.next());
                c=Double.parseDouble(input.next());
            }
            catch (NumberFormatException nfe) {
                System.out.println(" Not a number");
                continue;
                }
于 2013-10-27T19:16:57.367 回答