Mike Eghtebas
asked on
Exception...
In the attached code user is to enter two integers and get their sum.
It is supposed to throw exception:
-if the entry was more than two:
2 4 <-- is correct
2 3 7 <--not correct has three numbers
-if both not integer (float string, etc)
After giving the error, it is supposed to ask user to enter it again.
Thank you.
It is supposed to throw exception:
-if the entry was more than two:
2 4 <-- is correct
2 3 7 <--not correct has three numbers
-if both not integer (float string, etc)
After giving the error, it is supposed to ask user to enter it again.
Thank you.
import java.util.Scanner;
public class TestCalculator {
static int number1;
static int number2;
public static boolean isNumeric(String s) throws NumberFormatException {
boolean b = false;
String[] inputs = s.split(" ");
if(inputs.length==2)
{
try {
number1=Integer.parseInt(inputs[0]);
number2=Integer.parseInt(inputs[1]);
b=true;
}
catch(NumberFormatException ex){
throw ex;
}
}
return b;
}
public static void main(String[] args) {
boolean terminate=false;
while(terminate==false) {
Scanner input=new Scanner(System.in);
String str = input.nextLine();
terminate=(isNumeric(str));
System.out.println(number1+number2+"\n");
}
}
}
this is how it works:
import java.util.Scanner;
public class TestCalc1 {
static int number1;
static int number2;
public static boolean isNumeric(String s) throws NumberFormatException, WrongNumberOfInputsException {
boolean b = false;
String[] inputs = s.split(" ");
if(inputs.length==2)
{
try {
number1=Integer.parseInt(inputs[0]);
number2=Integer.parseInt(inputs[1]);
b=true;
}
catch(NumberFormatException ex){
throw ex;
}
} else
throw new WrongNumberOfInputsException("need two args");
return b;
}
public static void main(String[] args) {
boolean terminate=false;
while(terminate==false) {
Scanner input=new Scanner(System.in);
String str = input.nextLine();
try{
terminate=(isNumeric(str));
} catch(Exception ex){
System.out.println(ex);
}
System.out.println(number1+number2+"\n");
}
}
}
class WrongNumberOfInputsException extends Exception {
String s;
public WrongNumberOfInputsException(String s){
this.s = s;
}
public String toString() {return s;}
}
Output:
2
need two args
0
2
need two args
0
3 4 5
need two args
0
2 3
5
ASKER CERTIFIED SOLUTION
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
ASKER
Thank you
It wil be something like below, you also need to wrute a short class
with that another exception
Open in new window