1) Design a Java program, customize the Exception class, enter a string from the keyboard, if the string value is "ABC", throw exception information, if you enter from the keyboard other strings, do not throw an exception.
Import Java.util.Scanner;
Class MyException extends exception{
Private String errormsg;
Getter and Setter methods
Public myexception (String errormsg) {
this.errormsg=errormsg;
}
@Override
Public String toString () {
return errormsg;
}
}
public class Ex11 {
public static void Main (string[] args) {
String Strin;
Scanner scan=new Scanner (system.in);
Strin=scan.nextline ();
try {
if (Strin.equals ("abc"))
throw new MyException ("The string entered is incorrect! “);
} catch (MyException e) {
System.out.println (e);
}
}
}
2) Design a Java program, enter two numbers from the keyboard, perform subtraction operations. When the input string contains non-digits, the program works by using the exception handling mechanism.
Import java.util.*;
public class Ex12 {
public static void Main (string[] args) {
int num1,num2;
Scanner in=new Scanner (system.in);
try {
Num1=in.nextint ();
} catch (Inputmismatchexception e) {
System.out.println ("The first number is not formatted");
num1=0;
}
try {
Num2=in.nextint ();
} catch (Inputmismatchexception e) {
System.out.println ("The second number is not formatted");
num2=0;
}
System.out.println ("num1-num2=" + (num1-num2));
}
}
3) The custom exception class, when the subtraction operation, when the first number is greater than the second number, throw "minuend can not be less than the", and write a program to test.
Import Java.util.Scanner;
Definition of MyException class (with 11th question)
public class Ex13 {
public static void Main (string[] args) {
int num1,num2;
Scanner scan=new Scanner (system.in);
Num1=scan.nextint ();
Num2=scan.nextint ();
try {
if (num1<num2)
throw new MyException ("Minuend cannot be less than meiosis");
} catch (MyException e) {
System.out.println (e);
}
}
}
Java face question (05)