我是初学者,我正在从Deitel进行练习如何编程我制作分析考试结果的程序,并输出奖金是否给教师。我的程序工作正常,但我想如果用户输入1或2以外的值,那么它应该给出错误并终止程序。
Following is the code:
package test;
import java.util.Scanner;
public class apple {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
int failure = 0;
int passes = 0;
int counter = 1;
while (counter <= 10){
System.out.print("Enter Result (For Pass Enter 1 or for Fail Enter 2): ");
int result = input.nextInt();
if (result == 1)
passes = passes + 1;
else
failure = failure + 1;
counter = counter + 1;
}
System.out.printf("Total Pass Students are %d and Failed are %d" ,passes , failure );`enter code here`
if (passes > 8)
System.out.println("\nBonus to instructor");
}
}
答案 0 :(得分:0)
如何为其他号码抛出异常?您应该使用自己的非常规异常,因此请使用适当的类扩展异常替换它。
if (result == 1)
passes = passes + 1;
else if (result == 2)
failure = failure + 1;
else
throw new Exception("Wrong value");