Почему я все еще получаю InputMissmatchException, хотя у меня есть оператор catch - PullRequest
0 голосов
/ 05 ноября 2018
System.out.print("What kind of array do you want to create?\n1. Integer Array\n2. Double Array\n3. String Array\nYour Answer: ");
String input;
int num1 = 0;
try {
    input = s.next();
    num1 = Integer.parseInt(input);
    while (num1 > 3 || num1 < 1) {
        System.out.print("Please enter one of the three available options.\nYour Answer: ");
        input = s.next();
        num1 = Integer.parseInt(input);
    }
} catch (InputMismatchException e) {
    System.out.println("Do not enter a letter/special character");
}

Таким образом, я в основном задаю вопрос пользователю, спрашивающему его, какой массив он хочет создать. Но когда я пытаюсь сломать его и вставить Char / String, я получаю сообщение об ошибке, и программа завершается.

Ответы [ 2 ]

0 голосов
/ 05 ноября 2018

s.next() читает String из Scanner. Поэтому, если вы введете нечисловой String, он не выдаст InputMismatchException. Вместо этого Integer.parseInt выдает NumberFormatException при попытке разобрать это String как int, и вы не поймаете это исключение.

Возможно, вы захотите попробовать что-то вроде этого:

Scanner s = new Scanner (System.in);
System.out.print("What kind of array do you want to create?\n1. Integer Array\n2. Double Array\n3. String Array\nYour Answer: ");
String input;
int num1 = 0;
input = s.next();
try {
  num1 = Integer.parseInt(input);
}
catch (NumberFormatException numEx) {
  System.out.println("Do not enter a letter/special character");
}
while (num1 > 3 || num1 < 1) {
  System.out.print("Please enter one of the three available options.\nYour Answer: ");
  input = s.next();
  try {
    num1 = Integer.parseInt(input);
  }
  catch (NumberFormatException numEx) {
    System.out.println("Do not enter a letter/special character");
  }
}
0 голосов
/ 05 ноября 2018

Добавьте блок try-catch внутри цикла while. В противном случае исключение перехватывается после цикла, и когда вы обрабатываете исключение (в блоке catch), вы продолжаете выполнение потока, не прося пользователя повторить попытку.

Это не то, что вызывает вашу проблему, хотя. Если вы хотите просто напечатать ошибку и продолжить, вам следует переключить код на nextInt() вместо next() и parseInt(). Тогда исключение будет правильным, и его будет легче читать. (В настоящее время вы, вероятно, получаете NumberFormatException, когда вы пытаетесь анализировать String в Int вместо исключения при вводе - если вы хотите сделать это таким образом, измените исключение, которое вы пытаетесь перехватить)

int num1 = 0;
try {
    num1 = s.nextInt();
    while (num1 > 3 || num1 < 1) {
        System.out.print("Please enter one of the three available options.\nYour Answer: ");
        num1 = s.nextInt();
    }
} catch (InputMismatchException e) {
    System.out.println("Do not enter a letter/special character");
}
...