Jump to content

Integer.parseInt() - efficiency?

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
3 replies to this topic

#1
ZipOnTrousers

ZipOnTrousers

    Learning Programmer

  • Validating
  • PipPipPip
  • 94 posts
When using Integer.parseInt(), what would be the most efficient way of dealing with potential bad input? i.e. if the user entered a letter rather than an integer character? I realise this throws a NumberFormatException, but from what I've heard try catch shouldn't be used to control flow like this. Is there any other cleaner way to do this?

#2
ZekeDragon

ZekeDragon

    Writes binary right handed and hex left handed

  • Moderators
  • 2,103 posts
Here's another situation where my opinion I guess sharply contradicts others. In this situation, I have never noticed any significant performance penalty by simply trying the input and catching a NumberFormatException when the input was bad. However, if you're not satisfied with this answer, you can try Scanner:
[highlight=Java]import java.util.Scanner;

public class Main
{
public static void main(String[] args)
{
if (args.length > 1)
{
for (int iii = 0; iii < args.length; ++iii)
{
Scanner scn = new Scanner(args[iii]);

if (scn.hasNextInt())
{
int anum = scn.nextInt();
doSomethingWithInt(anum);
}
}
}
}
}[/highlight]
Though, in my opinion, the Integer.parseInt() + check for NFE is fine.
Wow I changed my sig!

#3
ZipOnTrousers

ZipOnTrousers

    Learning Programmer

  • Validating
  • PipPipPip
  • 94 posts
Thanks for the reply ZekeDragon, I did decide to just throw and catch the exception as I couldn't be bothered with the hassle of finding some fancy solution. Thanks!

I'm using this for a do while loop that constantly loops round asking the user to choose between 1-4 or 0, 1-4 being menu commands and 0 being the command to exit. Once I've caught the exception, is there any way to return to this loop so that the program effectively catches the exeption, displays a message and returns to normal operation? Or am I stuck with the program catching the exception and terminating?

#4
ZekeDragon

ZekeDragon

    Writes binary right handed and hex left handed

  • Moderators
  • 2,103 posts
Yes, that's what exceptions were designed for, so your program could gracefully handle unexpected situations. Here's a code example:
[highlight=Java]do
{
int parsedVal = -1;
try
{
parsedVal = Integer.parseInt(getUserInput()); // You'd display the menu in that function.
}
catch (NumberFormatException e)
{
System.out.println("Invalid input, please input a different number");
parsedVal = -1;
continue;
}
performAction(parsedVal); // If parsedVal < 1, ignore.
} while (parsedVal != 0);[/highlight]
You'll have to have the try/catch block inside of the do-while loop, however there shouldn't be any significant problems.
Wow I changed my sig!