Java – allows users to enter only positive integers (no decimals or strings)?
•
Java
I know how to ask users to enter positive integers, but I don't know how to handle code to avoid input errors, such as decimal or string input
int seedValue; double angle,gunpowder; System.out.println("Please enter a positive integer seed value: "); seedValue = input.nextInt(); while (seedValue <= 0) { System.out.println("Please enter a positive integer seed value: "); seedValue = input.nextInt(); } System.out.println("That target is " + threeDec.format(gen.nextDouble() * 1000) + "m away.");
Solution
This may be an approval:
>Using scanner Readline() reads the input as a string value; > Try using integer The parseInt method converts the string to int. if the input string contains decimals and invalid numbers, this method will throw numberformatexception. > If the input value was parsed correctly in the previous step, check whether it is negative
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码