Marcus Burkhart
Marcus Burkhart

Reputation: 195

Java prevent users from entering anything except integers

My intentions are to take a string input from a user, and only accept integer values. Maybe what I have is not the best approach to this and if that's the case let me know how I should go about changing my program. Lets say the user enters the values such as 1 2 3 4 a 5. How do I go about preventing this little error.

String[] intVal;
String inputValues;
int[] numbers = new int[20];
int count = 0;

InputStreamReader reader = new InputStreamReader(System.in);
BufferedReader input = new BufferedReader(reader);

System.out.print("Enter up to 20 integer values here: ");
inputValues = input.readLine();
intVal = inputValues.split("\\s");

for(int i = 0; i < intVal.length; i++){
   numbers[i] = Integer.parseInt(intVal[i]);
   count++;
}

Upvotes: 3

Views: 1797

Answers (2)

Maroun
Maroun

Reputation: 95958

Many possible solutions, one of them is catching the exception that parseInt throws and ask the user to input another sequence.

But I would use nextInt and hasNextInt instead, and ignore any character that's not a digit.

Upvotes: 0

Stefan
Stefan

Reputation: 1433

Integer.parseInt(String s) throws a NumberFormatException if the input was not a number (see the Javadoc on Integer.parseInt(String s)).

You could do something like

for (int i = 0; i < intVal.length; i++) {
  try {
    numbers[i] = Integer.parseInt(intVal[i]);
    count++;
  }
  catch (NumberFormatException ex) {
    System.out.println(i + " is not a number. Ignoring this value..."); // Or do something else
  }
}

Upvotes: 5

Related Questions