我遇到了 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
}
}