In: Computer Science
Create a moderately complex java program that utilises 2 or more
classes. Within these classes:
- have one that defines an exception
- have that exception throw(n) in one method and handled in
another
-has the program continue even if the user inputs incorrect
data
-be creative/unique in some way
import java.util.InputMismatchException;
import java.util.Scanner;
class MyNegativeNumberException extends RuntimeException{
public MyNegativeNumberException(String m) {
super(m);
}
}
public class TestEx {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter numbers (0 to exit): ");
int n=sc.nextInt();
int sum=0;
while(n!=0) {
try {
checkIfNegative(n);
sum+=n;
}
catch (InputMismatchException e) {
sc=new Scanner(System.in);
}
catch (MyNegativeNumberException e) {
System.out.println(e);
}
n=sc.nextInt();
}
System.out.println("Sum = "+sum);
}
private static void checkIfNegative(int n) throws MyNegativeNumberException{
if(n<0)
throw new MyNegativeNumberException("Invalid number");
}
}
Note : Please comment below if you have concerns. I am here to help you
If you like my answer please rate and help me it is very Imp for me