-2

I am trying to create an input that will Verify the input is an Integer, and that it is positive. Right now i have this. How should i check if the integer is positive

EDIT: Also i need it to keep asking until you enter a positive integer

        /**
 * pre: none
 * post: returns a positive integer as entered by the user
 */
public static int getInput(){
    int a;
    Scanner scan = new Scanner(System.in);
    System.out.println("Enter Desired Quantity.");

    while (!scan.hasNextInt()){ //Checks if input is Integer
        System.out.println("Enter A Positive Integer");
        scan.next();

    }
    a = scan.nextInt(); //Assigns entered integer to a
    return a; //replace with correct code
}
james.garriss
  • 11,468
  • 6
  • 75
  • 94
Tolkingdom
  • 67
  • 1
  • 1
  • 7

3 Answers3

4

You can do this in a single loop, similar to the one that you have for skipping invalid input. However, since the loop needs to ensure two things (i.e. a number is entered, and that number is positive) you need to modify its body.

Since the input needs to be done at least once, a do/while loop is a better choice.

Start with a loop that satisfies the condition that you want, i.e. "I got a number, and that number is positive":

int num = -1;
do {
    // We'll provide content of this in a moment
} while (num <= 0);

Once the loop exits, you know that num > 0, so the only task now is to write a body of the loop that takes us closer to that goal.

Inside the loop we need to check that the user entered a number. If he did, we harvest that number; otherwise, we tell the user to try again:

System.out.print("Please enter a positive integer number: ");
if (scan.hasNextInt()) {
    num = scan.nextInt();
} else {
    System.out.println("I need an int, please try again.");
    scan.nextLine();
}

That's it - now you have a loop body that reads the value for you, and a loop condition that ensures that the value is positive on exit. Combine the loop with the loop body, and try it out. It should do the trick.

Sergey Kalinichenko
  • 675,664
  • 71
  • 998
  • 1,399
1

Simple:

Scanner input = new Scanner(System.in);

System.out.print("Enter a number: ");
int number = input.nextInt();

if( number == 0)
{ System.out.println("Number is zero"); }
else if (number > 0)
{ System.out.println("Number is positive"); }
else 
{ System.out.println("Number is negative"); }

On a side note:

Check Math.signum()

Returns the signum function of the argument; zero if the argument is zero, 1.0 if the argument is greater than zero, -1.0 if the argument is less than zero.

Rahul Tripathi
  • 152,732
  • 28
  • 233
  • 299
0

You can try this:

public static int getInput(){
   Scanner scan = new Scanner(System.in);

   System.out.println("Enter Desired Quantity.");
   int a = scan.nextInt();
   while (a  < 0){ //Checks if input is Integer
       System.out.println("Enter A Positive Integer");
       a = scan.nextInt();

   }

   return a;
}
qbit
  • 2,528
  • 2
  • 12
  • 27