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.