1

I have to make a store that has items for purchase. After choosing an item, I prompt the user to enter the quantity of the item they would like to buy.

// 'input' is my Scanner object
int quantity;
quantity = input.nextInt();

If the user enters a non-integer (i.e. decimal, char...), it breaks the program. Is there a way I can validate for this non-integer input?

Thank you

camburglar
  • 11
  • 4
  • I recommend reading: [Lesson: Exceptions](https://docs.oracle.com/javase/tutorial/essential/exceptions/index.html) – Jacob G. Sep 20 '19 at 20:50
  • `nextInt()` float, byte, etc are great when you're reading from a datastream, but user input typed by a human is pretty unpredictable. You'll generally have to read everything as _Strings_, then validate that the string represents the thing you wanted. – Stephen P Sep 20 '19 at 20:52
  • @StephenP in general I agree with you, but even in the case of datastreams I would recommend taking a string value and then attempting to cast it to the expected type. The scars of trusting others code run long and deep. – hooknc Sep 20 '19 at 21:00
  • Use `hasNextInt()` before attempting to call `nextInt`. – Andreas Sep 20 '19 at 21:03
  • @hooknc agreed. I, in fact, have _never_ used `java.util.Scanner` – Stephen P Sep 20 '19 at 21:40

2 Answers2

3

Sure, accept a String value instead of an int, check to see if you can parse that String value to an int, if you can, then do so. If not, sent a message stating that then entered value must be an number.

This could be done in a while loop.

import java.util.Scanner;

public class ScannerInputInt {

    public static void main(String... args) {

        Scanner in = new Scanner(System.in);

        Integer input = null;

        do {

            System.out.println("Please enter number: ");

            String s = in.nextLine();

            try {

                input = Integer.parseInt(s);

            } catch (NumberFormatException e) {

                System.out.println("ERROR: " + s + " is not a number.");
            }

        } while (input == null);
    }
}
hooknc
  • 4,253
  • 4
  • 30
  • 53
  • *"check to see if you can cast that String value to an int"* That can never be done. Calling `Integer.parseInt` is not *casting*. `input = (Integer) s;` would be *casting*. – Andreas Sep 20 '19 at 21:06
  • @Andreas fair enough. Changed the wording... – hooknc Sep 21 '19 at 14:26
0

If you don't wanna use Exceptions method. You can try this.

This piece of code will continue to ask user input until user has entered correct input.

System.out.print("Enter quantity: ");
Scanner input = new Scanner(System.in);
boolean isInt = input.hasNextInt(); // Check if input is int
while (isInt == false) { // If it is not int
   input.nextLine(); // Discarding the line with wrong input
   System.out.print("Please Enter correct input: "); // Asking user again
   isInt = input.hasNextInt(); // If this is true it exits the loop otherwise it loops again
}
int quantity = input.nextInt(); // If it is int. It reads the input
System.out.println("Quantity: " + quantity);
input.close();

Output:

Enter quantity: 12.2
Please Enter correct input: 12.6
Please Enter correct input: s
Please Enter correct input: s6
Please Enter correct input: as
Please Enter correct input: 2
Quantity: 2

I think it is slightly better approach because I think controlling flow of your program with Exceptions is bad practice and should be avoiding when there are other things that you can use.

Goion
  • 923
  • 8
  • 16