0

Why it's displays error I can't find it. Can you explain me in detail? Why it's happening?

import java.util.*; class stack { public static void Push(int top, int[] stack) { Scanner sc = new Scanner(System.in); if (top == stack.length - 1) { System.out.println("Stack Overflow"); System.exit(1); } else { System.out.println("Pushed element in Stack: "); int n = sc.nextInt(); ++top; stack[top] = n; } sc.close(); } public static void Pop(int top, int[] stack) { if (top == -1) { System.out.println("Stack Empty"); System.exit(1); } else { int item = stack[top]; top--; System.out.println("Deleted item: " + item); } } public static void Disp(int top, int[] stack) { if (top == -1) { System.out.println("Stack Empty"); } else { for (int a : stack) { System.out.println(a); System.out.println(); }

31st Jan 2024, 3:56 PM
Sudip
3 Respostas
+ 5
Why do you tag Python when it is Java? Which error do you get? Link your code, so people can test it.
31st Jan 2024, 4:19 PM
Lisa
Lisa - avatar
+ 1
- keep System.in opened, if you close it, (by sc.close() ) it is imposible read it again ! - also if you change the int variable 'top' inside methods push(), pop(), it does not affect the 'top' outside the methods (in main() ) rest of code: System.out.println("Unknown command " +choice); } // test System.out.println( Arrays.toString(stack)); System.out.println( "top="+top); } } }
1st Feb 2024, 8:40 AM
zemiak
0
Lisa PS S:\Java_DSA> javac stack.java PS S:\Java_DSA> java stack Enter size of stack: 4 Enter your choice: 1. Push 2. Pop 3. Display 4. Exit Enter your choice: 1 Pushed element in Stack: Exception in thread "main" java.util.NoSuchElementException at java.base/java.util.Scanner.throwFor(Scanner.java:945) at java.base/java.util.Scanner.next(Scanner.java:1602) at java.base/java.util.Scanner.nextInt(Scanner.java:2267) at java.base/java.util.Scanner.nextInt(Scanner.java:2221) at stack.Push(stack.java:12) at stack.main(stack.java:63)
5th Feb 2024, 1:21 PM
Sudip