Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Only let users input positive integers (no decimals or strings)?

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.");
like image 423
Jake Avatar asked Sep 14 '13 18:09

Jake


People also ask

How do you make input only accept positive numbers?

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.

How do you accept only positive integers in python?

If you want to restrict the <input> field to only positive numbers, you can use the min attribute.

How do you declare a positive integer in Python?

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.

Is an integer only positive?

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.


1 Answers

This may be an approch:

  • Read the input as a string value using Scanner.readLine();
  • Try to convert the string to int using Integer.parseInt method. This method will throw a NumberFormatException in case the input string contains decimals and invalid digits.
  • if the input value is parsed properly in previous step, then check for negative
like image 117
Juned Ahsan Avatar answered Oct 15 '22 09:10

Juned Ahsan