Claudio Lopez Claudio Lopez - 4 months ago 13
Java Question

java simple add two numbers program - Exception Handler not working

The try exception is not doing its job. I enter whatever strings instead of float numbers and it does not display error message "NumberFormatException"
What am I doing wrong?

import java.util.*;

public class Sum {

public float sum1;
public float sum2;
public static float total;

public static void main(String[] args) {
Sum sum = new Sum();
Scanner sc = new Scanner(System.in);

System.out.println("Enter the first digit: ");
sum.sum1 = sc.nextFloat();

float sum1;
float sum2;
try {
sum1 = Float.parseFloat(null);
sum2 = Float.parseFloat(null);
} catch (NumberFormatException e) {
System.err.println("NumberFormatException");
}

System.out.println("Enter the second digit: ");
sum.sum2 = sc.nextFloat();
total = sum.sum1 + sum.sum2;
System.out.println("Total sum is: " + total + "\n");
System.out.println("***************************************************************************************");
System.out.println("If you need to add numbers again please press play button on top of the eclipse program");
}


}

Answer

The error you are getting is from the scanner that wants a float but is getting a string. You want to accept a String and try to parse it to a float. Furthermore you need to set sum1 and sum2 to be static so they can be used inside the main function and remove your second deceleration as that simply fixes your scope problem but makes the class declarations pointless. Try something more like this:

import java.util.*;
public class Sum {

    public static float sum1;
    public static float sum2;
    public static float total;

    public static void main(String[] args)  {
           Sum sum = new Sum();
           Scanner sc = new Scanner(System.in);

           try {
               System.out.println("Enter the first digit: ");
               sum1 = Float.parseFloat(sc.nextLine());
               System.out.println("Enter the second digit: ");
               sum2 = Float.parseFloat(sc.nextLine());
           } catch (NumberFormatException e) {
               System.err.println("NumberFormatException");
           }
           total = sum.sum1 + sum.sum2;
           System.out.println("Total sum is: " + total + "\n");
           System.out.println("***************************************************************************************");
           System.out.println("If you need to add numbers again please press play button on top of the eclipse program");
    }
}