Could anyone please explain to me why the add() method returns 0 instead 4?
I am trying to use int 0 in case “invalid” string number is provided (e.g. four).
I am getting the right results for String arguments 3,4 / 3,four / three,four / but not for three, 4.
Can you please give me hints what I am doing wrong?
Thanks!
public class Numbers2
{
public static void main(String[] args) {
System.out.println(add("d","4"));
} // main() method
public static int add(String a, String b)
{
int x = 0;
int y = 0;
try{
x = Integer.parseInt(a);
y = Integer.parseInt(b);
System.out.println("No exception: " + (x+y));
return x + y;
}
catch (NumberFormatException e){
if(x != (int) x ){
x = 0;
}
if(y != (int) x ){
y = 0;
}
return x + y;
}
} // add() method
} // class
The problem is that the line
y = Integer.parseInt(b);doesn’t get the chance to execute as you are passing"d"as the first argument which is not an integer, the linex = Integer.parseInt(a);results in exception and bothxandyremain 0.You could solve the problem by using separate try/catch for both: