Link to home
Start Free TrialLog in
Avatar of Mike Eghtebas
Mike EghtebasFlag for United States of America

asked on

Revise to include Exception handling

Below, there is CalculatorTest.java attached. The error handling in it mostly via some if statements etc.

Question: What is the best way to use java Exception handling routines to improve it?


import java.text.DecimalFormat;

public class CalculatorTest{
    

   public static boolean isNumeric(String s) {

        boolean b = true;

        try {
          float f = Float.parseFloat(s);
        }
        catch(Exception ex){
            b = false;
        }
            return b;
        }

        public static String validData(String [] ss){

            String temp="";

            if(!isNumeric(ss[0])) {
                temp= "Wrong Input: " + ss[0];
            }else if(!isNumeric(ss[2])) {
                temp= "Wrong Input: " + ss[2];
            }else if(Double.parseDouble(ss[2])==0.0 && ss[1].charAt(0)=='/') {
                temp= "Division by zero";
            }
            return temp;
        }

        public static String validInput(String [] ss){

//                 for(String s: ss){
//                System.out.println(s);
//            }

            String temp="";

//            System.out.println("Im here");
            if (ss.length !=3) {
                temp = "Usage: java Calculator operand1 operator operand2\n";

            }else if(!ss[1].equals("+") && !ss[1].equals("-") && !ss[1].equals("*") && !ss[1].equals("/")){
                temp = "Usage: java Calculator operand1 operator operand2\n"+
                       "       (Make sure to have * inside \"*\" as shown here.";}
            return temp;
        }

        public static void main(String[] args) {

//            for(String s: args){
//                System.out.println("|"+s+"|");
//            }

            String errorMessage = validInput(args);

//            System.out.println("Test return: "+errorMessage+"\n");

            if(errorMessage.trim().length() != 0){

                System.out.println(errorMessage+"\n");

            }else{

                errorMessage = validData(args);

                if(errorMessage.trim().length() != 0){
                    System.out.println("Error: " + errorMessage + "\n");
                    
              //  }else if(errorMessage.toString()==""){
                //    System.out.println(errorMessage + "\n");
                }else{
                    printTheCalculationresult(args);
                }
            }
        }

        public static void printTheCalculationresult(String[] args)
        {
            System.out.print("print The Calculation result: ");

            DecimalFormat df=new DecimalFormat("0.##");
            double result=0.0;


            switch (args[1].charAt(0)){
                case '+': result=(int) Double.parseDouble(args[0]) +
                                 (int) Double.parseDouble(args[2]);
                          break;
                case '-': result=(int) Double.parseDouble(args[0]) -
                                 (int) Double.parseDouble(args[2]);
                          break;
                case '*': result=(int)Double.parseDouble(args[0])*
                                 (int) Double.parseDouble(args[2]);
                          break;
                case '/': result=Double.parseDouble(args[0]) /
                                 Double.parseDouble(args[2]);
            }

            System.out.print(args[0]+ " " +    args[1] + " " + args[2] + " = "+  result+"\n\n");
    }
}

Open in new window

Avatar of for_yan
for_yan
Flag of United States of America image

What do you mean by that ?
You can throw execption in all these methods and catch them in the main() program
from the place where you call them

And better to use one validation method rather than to split it between two or more
this is an example :
change to 2 + a (instead of 2 + 3) and it will catch custom exception

import java.text.DecimalFormat;

public class TestCalculator {

   public static boolean isNumeric(String s) {

        boolean b = true;

        try {
          float f = Float.parseFloat(s);
        }
        catch(Exception ex){
            b = false;
        }
            return b;
        }

        public static void  validData(String [] ss) throws InvalidDataException {

            String temp="";

            if(!isNumeric(ss[0])) {
                temp= "Wrong Input: " + ss[0];
            }else if(!isNumeric(ss[2])) {
                temp= "Wrong Input: " + ss[2];
            }else if(Double.parseDouble(ss[2])==0.0 && ss[1].charAt(0)=='/') {
                temp= "Division by zero";
            }

            if(temp.trim().length() >0)throw new InvalidDataException(" Input invalid: non-numeric operands or invaild operations");
            //return temp;
        }

        public static String validInput(String [] ss){

                 for(String s: ss){
                System.out.println(s);
            }

            String temp="";

            System.out.println("Im here");
            if (ss.length !=3) {
                temp = "Usage: java Calculator operand1 operator operand2\n";

            }else if(!ss[1].equals("+") && !ss[1].equals("-") && !ss[1].equals("*") && !ss[1].equals("/")){
                temp = "Usage: java Calculator operand1 operator operand2\n"+
                       "       (Make sure to have * inside \"*\" as shown here.";}

            

            return temp;
        }

        public static void main(String[] args) {

            for(String s: args){
                System.out.println(s);
            }

            String errorMessage = validInput(args);

            System.out.println("Test return: "+errorMessage+"\n");

            if(errorMessage.trim().length() != 0){

                System.out.println(errorMessage+"\n");

            }else{
                   try{
               validData(args);
                   }catch(InvalidDataException ex){
                      System.out.println( ex.toString());
                       ex.printStackTrace();
                        System.out.println("Error: " + errorMessage + "\n\n" +
                        "Usage: java Calculator operand1 operator operand2\n");
                       System.exit(0);
                   }



                    printTheCalculationresult(args);
                }
            }
        

        public static void printTheCalculationresult(String[] args)
        {
            System.out.print("print The Calculation result: ");

            DecimalFormat df=new DecimalFormat("0.##");
            double result=0.0;

            switch (args[1].charAt(0)){
                case '+': result=(int) Double.parseDouble(args[0]) +
                                 (int) Double.parseDouble(args[2]);
                          break;
                case '-': result=Integer.parseInt(args[0]) -
                                 Integer.parseInt(args[2]);
                          break;
                case '*': result=(int)Double.parseDouble(args[0])*
                                 (int) Double.parseDouble(args[2]);
                          break;
                case '/': result=Integer.parseInt(args[0]) /
                                 Integer.parseInt(args[2]);
            }

            System.out.print(args[0]+ " " +    args[1] + " " + args[2] + " = "+  df.format(result)+"\n\n");

           
            
    }
}
class InvalidDataException extends Exception {
    String mistake;
    public  InvalidDataException(String err)
     {
       super(err);     // call super class constructor
       mistake = err;  // save message
     }

    public String toString(){
        return mistake;
    }

    

}

Open in new window

Avatar of Mike Eghtebas

ASKER

Using NumberFormatException and/ or creating our own exception class.
The above is example with our own exception class
NumberFormatException is a subclass of the Runtime Exception class.  A Number Format Exception occurs in the java code when a programmer tries to convert a String into a number. The Number might be int,float or any java numeric values.

How can include NumberFormatException with it?
re:> The above is example with our own exception class

I am learning but what I meant to have a separate Exception class where we can instantiate it in our main() and use it that way. However, finding use and reference to NumberFormatException is my prime goal.  
Yes number formaty excpetion will be thwon if  Integer.parseInt("abc") - so you can catch it and re-thow back from your method
The above code does have separate execption class - see below
You dont nweed to instantiate sException class necessaruily in main() - you need  to do it
when you throw exception - look at the code above
ASKER CERTIFIED SOLUTION
Avatar of for_yan
for_yan
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial