如何捕捉非数值?

时间:2013-10-27 18:21:46

标签: java

我遇到了问题& amp;抓住。要求是它必须在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
        }
    }

5 个答案:

答案 0 :(得分:0)

后面有语法错误
} while (a==(double)a && b==(double)b && c==(double)c);

在此行之后加上}。你的程序似乎适合我。

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

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

答案 3 :(得分:0)

您正在捕获错误类型的异常,并且您收到的错误消息告诉您。当令牌(在本例中为输入中的文本)不是浮点数时,Scanner.nextDouble()方法抛出InputMismatchExceptionNumberFormatExceptionDouble.parseDouble()方法引发,而不是由扫描程序引发。

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

答案 4 :(得分: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
}

}