A program is written that adds and removes elements from the Stack by the command that the user entered. The fact is that if instead of a digit on the input you write any character, for example, “a,” then the program will throw an InputMismatchException. Here is the program code:

class Main { public static void showpush(Stack st, String a) { st.push(new String(a)); System.out.println("Добавлен(" + a + ")"); System.out.println("Стек: " + st); } public static void showpop(Stack st) { if (st.empty()) System.out.println("Вы пытаетесь извлечь элемент из пустого стека"); else { System.out.print("Удалён элемент -> "); String a = (String) st.pop(); System.out.println(a); System.out.println("Стек: " + st); } } public static void main(String[] args) { System.out.println("На ввод команды приниются только цифры"); Scanner sc = new Scanner(System.in); Stack st = new Stack(); System.out.println("Стек: " + st); int komanda=0; try { while (komanda != 666) { System.out.println("Чтобы добавить элемент в стек напишите 1, чтобы извлечь - 2, остановить - 666"); komanda = sc.nextInt(); if (komanda == 1) { String dobav; System.out.println("Введите элемент: "); dobav = sc.next(); showpush(st, dobav); } else if (komanda == 2) { showpop(st); } } } catch (InputMismatchException e) { System.out.println("На ввод принимаются только цифры"); } System.out.println("Процесс остановлен"); } } 

I tried to catch InputMismatchException inside the loop, but when an error is output, the loop starts working endlessly, because variable we have already set. And if we try and catch within the While loop, then after the trigger the loop stops working, and I would like the user to be given the opportunity to enter the command again.

  • "since we have already set a variable" - which one? - Enikeyschik
  • The variable is set from the keyboard in the line komanda = sc.nextInt (); - THAT GUY

1 answer 1

Before scanner.nextInt() check if there is an integer value there using the method scanner.hasNextInt() - this will not catch the exception, not to mention the fact that catching the exception is a rather expensive operation, and it is ugly :)

Update

Like that:

 if(!sc.hasNext()) //чтобы не было вечного цикла break; if(sc.hasNextInt()) //проверяем есть ли целое число komanda=sc.nextInt(); //читаем else { komanda=0; continue; //продолжаем цикл } 
  • And how can I use this example to implement it? Do not quite understand. If you remove try / cacth and write sc.hasNextInt (); before komanda = sc.nextInt (); it doesn't work out - THAT GUY
  • Do you know how to burn? See the update - Barmaley
  • Only in this semester I started learning Java, so I wouldn’t say THAT GUY
  • And where is Java - the language does not play a role, did they probably learn pascal or python at school? - Barmaley
  • one
    It starts to bother me - as if I did not work for you to write code. You just think over all the logic yourself - I’m writing on my knees, and you have a debugger, IDE and all that. Spoiler: sc.hasNext() should be entered into the else branch, and the while() conditions should be slightly reformulated. In general, that's all - good luck! - Barmaley