简体   繁体   中英

how do i prevent the scanner from accepting strings, negative integers, or numbers less than 2?

How do i prevent negative numbers from being returned by this method? I have tried setting the while loop to

(n < 0 && n != 0)

to no avail. Here is my code for the method currently:

public int getNumber() {          
       int n = 1;
       while(n < 2 && n != 0) {
           if(n < 0) {
               System.out.print("Error, please enter a valid number greater than 0(0 to exit): ");               
               scan.next();
               n = scan.nextInt();
           }
       try {           
           System.out.print("Enter the upper bound(0 to exit): ");
           n = scan.nextInt();           
           break;
       }
       catch(java.util.InputMismatchException e) {
           System.out.print("Error, please enter a valid number greater than 0(0 to exit): ");
           scan.next();
           continue;
           }      
       }
       return n;      
   } 

I have also tried to put my if statement inside the try block like this:

public int getNumber() {          
       int n = 1;
       while(n < 2 && n != 0) {

       try {           
           System.out.print("Enter the upper bound(0 to exit): ");
           n = scan.nextInt();
           if(n < 0) {
               System.out.print("Error, please enter a valid number greater than 0(0 to exit): ");               
               scan.next();
               n = scan.nextInt();
           }
           break;
       }
       catch(java.util.InputMismatchException e) {
           System.out.print("Error, please enter a valid number greater than 0(0 to exit): ");
           scan.next();
           continue;
           }      
       }
       return n;      
   }

When i put the if statement inside the try block, i started to input negative numbers consecutively to test. It worked for the first time i entered a negative number, then gave me a blank scanner input line, and then finally allowed a negative number to return, which in turn screws the rest of my program up. Please help, im a first semester student in java. Thank you.

You input a negative number, then it goes into your n<0 if and you put in another one and then break out of the loop. Try changing your if to:

while(n < 0) 

Do not use while loop condition for validating input. Your loop condition does not give your program a chance to accept and check the number before making a decision to keep or to reject the entered value. As the result, your program starts prompting end-users with an error message even before they typed anything.

You should not call nextInt without first checking if the Scanner is ready to give you an int by calling hasNextInt .

Finally, you need a rejection loop to throw away non-integer input until hasNextInt succeeds. This is usually done with a nested while loop, which prints an error prompt, and throws away the entered value.

The overall skeleton for reading and validating an int looks like this:

System.err.println("Enter a number between 0 and 5, inclusive");
int res = -1;
while (true) {
    while (!scan.hasNextInt()) {
        System.err.println("Incorrect input. Please enter a number between 0 and 5, inclusive");
        scan.nextLine(); // Discard junk entries
    }
    res = scan.nextInt();
    if (res >= 0 && res <= 5) {
        break;
    }
    System.err.println("Invalid number. Please enter a number between 0 and 5, inclusive");
}
// When you reach this point, res is between 0 and 5, inclusive

couldn't you just check for 'hasNextInt', then test the input.

int n = 0;
System.out.println("Enter a number between 0 and 5);
while (scan.hasNextInt()) {
    n = scan.nextInt();
    if (n >= 0 && n <= 5) {
        break;
    }else{
        //prompt error message or handle however you wish
    }
}
return n;

likewise you could also force with an unsigned integer.

Final code to not return negative integers or strings:

public int getNumber() {
       System.out.print("Enter the upper bound(0 to exit): ");
       int nums = 1;
       while(true) {
           while(!scan.hasNextInt()) {
               System.out.print("Error. Please enter a valid integer greater than 1(0 to exit): ");
               scan.nextLine();
           }
           nums = scan.nextInt();
           if(nums > 2 || nums == 0) {
               break;
           } else {
               System.out.print("Error. Please enter a valid integer greater than 1(0 to exit): ");
               scan.nextLine();
           }
       }
      return nums;
   }

Thanks a million you guys!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM