Java prevents users from entering anything other than integers

My intentions are to take string input from the user and only accept integer values. Perhaps what I have is not the best approach to this, and if this case tells me how I should change my program. Let's say the user enters values ​​such as 1 2 3 4 a 5

. How can I prevent 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++;
}

      

+3


source to share


2 answers


Integer.parseInt(String s)

emits a NumberFormatException

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

).

You can 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
  }
}

      

+5


source


Many possible solutions, one of which throws an exception that parseInt

throws and asks the user to enter a different sequence.



But I would use nextInt

and hasNextInt

and ignore any character that is not a number.

0


source







All Articles