Avatar of Mike Eghtebas
Mike Eghtebas
Flag for United States of America

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.
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");
        }

    }
       
}

Open in new window

Java

Avatar of undefined
Last Comment
Mike Eghtebas

8/22/2022 - Mon