我想测试一个程序,该程序通过在try-catch块中调用上述方法来提示用户输入字母等级并显示质量点。
import java.util.*;
import javax.lang.model.util.ElementScanner14;
public class Lab17 {
public static int qualityPoint(String alpha) {
if (alpha.equals("A+"))
return 4;
else if (alpha.equals("A"))
return (int) 3.75;
else if (alpha.equals("B+"))
return (int) 3.5;
else if (alpha.equals("B"))
return 3;
else if (alpha.equals("C+"))
return (int) 2.5;
else if (alpha.equals("C"))
return 2;
else if (alpha.equals("D+"))
return (int) 1.5;
else if (alpha.equals("D"))
return 1;
else if (alpha.equals("F"))
return 0;
else
throw new InputMismatchException("Invalid grade");
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a letter grade: ");
String alpha = sc.next();
try {
int res = qualityPoint(alpha);
System.out.println("The quality points " + alpha);
} catch (InputMismatchException ex) {
System.out.println("Exception: Enter just a letter grade");
}
}
}
输入字母等级:A.质量点A
我希望输出输入字母等级:A.质量点A或输入字母等级:x等级无效
您可能会弄错,使用res而不是alpha。
int res = qualityPoint(alpha);
System.out.println("The quality points " + res);