I am stuck on this question~:
The method Integer.parseInt converts a String of digits to the int number it denotes.
public static int parseInt (String s)
throws NumberFormatException
Explain how you could trap the exception thrown by parseInt and illustrate your answer with a code example.
My answer that I have thought of so far is:
try
{
System.out.println("incorrect");
}
catch (NumberFormatException n)
{
System.out.println("WRONG! This is not a number");
}
I have a feeling this answer is wrong because the code above would only be used in the main method and I'm not sure how I would trap the exception under:
public static int parseInt (String s)
throws NumberFormatException.
I've looked through java API for the parseInt method and looked via various research and tried doing the code, however I'm still struggling to get this right due to my lack of understanding.
If anyone could help me out, I'd be grateful, thanks in advance.
Since this is homework, I'll just give you a hint: you have to call the method, and surround the call with an appropriate try
-catch
block.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With