I know how to ask the user to input positive integers, but I don't know how approach the code to avoid an input error such as a 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.");
You can force the input to contain only positive integer by adding onkeypress within the input tag. Here, event. charCode >= 48 ensures that only numbers greater than or equal to 0 are returned, while the min tag ensures that you can come to a minimum of 1 by scrolling within the input bar.
If you want to restrict the <input> field to only positive numbers, you can use the min attribute.
abs() function returns an positive/absolute value of a given number. The return value depends on input parameter. If an input parameter is an integer then return value is an integer.
Integers are all the whole numbers, both positive and negative. By whole numbers we mean numbers without fractions or decimals. You can also call positive integers your 'counting numbers' because they are the same.
This may be an approch:
string
value using Scanner.readLine();
Integer.parseInt
method. This method will throw a NumberFormatException
in case the input string contains decimals and invalid digits.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