10th job (2)

Topic 2:

Enter the number 5, on behalf of student achievement, we calculate the average. When the input value is negative or greater than 100, custom exception handling prompt.

Test.java

/ * Defines an array with the for () loop input
* IF () statement determines thrown
* personal keyboard 5, the average score is calculated
* * /
Package COM;
Import java.util.Scanner;
class the Test {
Private static void A (int i) throws MyException {// declare the exception
if (i> 100 | i < 0) // if statement determines
the throw new new MyException (I);
}
public static void main (String [] args) {
Scanner Scanner new new SC = (the System.in);
int a [] = new new int [. 5]; // defines an array
System.out.println ( "Please enter an integer of 5");
int SUM = 0; // for calculating 5 and integer
int P = 0;
for (int I = 0; I <5; I ++) {// cycle through the input number 5
the try {
a (a [I] = sc.nextInt ());
SUM = SUM + A [I];
P = SUM /. 5;
} the catch (MyException E) {
e.printStackTrace (); // print anomalies
Of System.out.print ( "" + e.toString ());
}
}
System.out.println ( "GPA" + p); // output GPA
}
}

MyException.java

/ * Custom exception inherit the parent class exception
*
* * / COM Package;
class MyException the extends Exception {
public MyException (I int) {
of System.out.print ( "input error, the range of 0-100");
}
}

operation result

 

 

Guess you like

Origin www.cnblogs.com/LJTQ/p/11877658.html