Reputation: 13
In my simple program(below) that just checks if a number is odd or even, I think I have tested everything that the user(me) could possible do, and everything works unless the user inputs a string or double instead of an integer for numStr. I attempted to try{...}
and catch{...}
but the catch isn't catching the exception that is thrown.
If for example I enter "s" instead of an integer an error shows up saying
java.lang.NumberFormatException: For input string: "s"
Could you please help me?
import javax.swing.JOptionPane;
public class HowToUseJOptionPane
{
public static void main (String[] args)
{
String numStr, result;
int num, again = 1;
do
{
try
{
numStr = JOptionPane.showInputDialog("Enter an integer: ");
}
catch (NumberFormatException nfe)
{
System.out.println("Requires an integer, try again");
again = 0;
numStr = null;
}
while (numStr != null)
{
num = Integer.parseInt(numStr); //gets number
result = "That number is " + ((num % 2 == 0) ? "even" : "odd");
JOptionPane.showMessageDialog(null, result); //shows result
//JOptionPane.YES_OPTION =0, no = 1, cancel = 2
again = JOptionPane.showConfirmDialog(null, "Do another?");
numStr = null;
}
} while (again == 0);
}
}
Upvotes: 0
Views: 107
Reputation: 726589
You cannot catch the NumberFormatException
because you are looking for it in a wrong place.
The first thing you do to debug a situation like that is to check which method would throw the exception of interest. In this case that would be the Integer.parseInt
.
Once you identify the method, make sure the try
/catch
block includes the method call of interest. In your case, it does not, which means that your code would not catch the NumberFormatException
exception.
Moving the entire try
/catch
into the while
loop so that it encloses the call of Integer.parseInt
method would fix this issue.
Upvotes: 1
Reputation: 5723
You need to put the try block where you do the parsing:
try
{
num = Integer.parseInt(numStr); //gets number
}
catch (NumberFormatException nfe)
{
. . .
Upvotes: 3
Reputation: 2618
The problem is that you're trying to parse the number outside the try catch block. Place it inside the try catch block.
try
{
numStr = JOptionPane.showInputDialog("Enter an integer: ");
num = Integer.parseInt(numStr); //gets number
}
Upvotes: 0