Combine hasNextInt and value greater/less than X checks

Using the following method:

public void localsetValue(String UserInput) 
{
    System.out.println("Enter New Value:");
    while (!console.hasNextInt()){
            console.next();
            System.out.println("Must be a number.");
        }
        tempInt = console.nextInt();
        console.nextLine();



    while (tempInt <0) { 
        System.out.println("Value must be positive.");
        tempInt = console.nextInt();
    }
    SetSpecificValue(UserInput.toLowerCase(), tempInt);
}

The first while loop checks that the user enters a valid int; this works fine.

The second while loop checks that the user enters a positive number; this also works but at this point they can enter a letter and it'll throw out the exception.

Still new to Java, is there a way to combine these two checks?

Answers


Just use the same while loop and you'll be fine.

Here, we continue looping if user enters something other than an int OR if the entered int is negative.

int tmpInt = 0;
boolean flag = false;
while ((flag = !console.hasNextInt()) || (tmpInt = console.nextInt()) < 0){
    if (flag) {
        console.next();
        flag = false;
    }
    System.out.println("Value must be a positive integer !");
}

You only need one loop but have to combine the two abort conditions (is a number, is positive).

int value = -1
do {
   if(console.hasNextInt()){
      value = console.nextInt();
   } else {
      console.next();
   } 
} while(value < 0)

Something like this?

public void localsetValue(String UserInput) 
{
    tempInt = -1;
    System.out.println("Enter New Value:");
    while (!console.hasNextInt() || (tempInt = console.nextInt()) <0){
            console.next();
            System.out.println("Must be a positive number.");
        }     
        console.nextLine();
    SetSpecificValue(UserInput.toLowerCase(), tempInt);
}

Need Your Help

Global RegEx search and replace to fix HTML in an XML export file?

html xml regex text grep

I have a fairly large WordPress .XML export file from a blog that I am going to migrate to Drupal. One glaring issue with the export file is that it's missing &lt;p&gt; tags for any paragraph breaks.

Showing several alert views consecutively: only the last one shows

ios objective-c

I updated the question a bit with a very simple setup.