Skip to content

Commit 646c075

Browse files
committed
feat(StackDemo1): add interactive stack input and save contents to file
What - Added StackDemo1 class. - Used Scanner to take user input. - Created a Stack<Integer>. - Asked user how many elements to push. - Iteratively read integers and pushed them onto the stack. - Printed the stack contents. - Implemented saveStackToFile() method: - Used BufferedWriter + FileWriter to write each stack element to a file, one per line. - Wrapped file writing in try-with-resources for safe closure. - Closed Scanner after input. Why - Demonstrates interactive usage of Stack with user input. - Shows how to persist stack contents into a file. - Combines collections (Stack) with I/O (BufferedWriter) for practical example. How - User prompted for n. - For loop reads n integers via sc.nextInt() and pushes into stack. - After input, printed stack. - saveStackToFile() iterates stack, writes each value with newline. - File saved to hardcoded path. Logic - Inputs: integer count n and stack elements. - Outputs: - Printed stack contents. - Saved stack elements to text file. - Flow: 1. Prompt for size. 2. Read elements, push to stack. 3. Print stack contents. 4. Write contents to file. - Edge cases: - Non-integer input throws InputMismatchException. - File path invalid or lacking permissions → IOException caught and error message shown. - Empty stack still creates empty file. - Complexity: - Stack push O(1) per element. - File write O(n). - Concurrency: Stack is synchronized but Scanner/FileWriter are not thread-safe here. Real-life applications - Capturing runtime stack input from users. - Persisting stack state for later retrieval or debugging. - Useful template for combining data structures with file I/O. Notes - Hardcoded file path may fail across systems; should use relative paths or configurable paths. - Prefer try-with-resources for Scanner as well to ensure closure. - In modern code, ArrayDeque often replaces Stack, but demo illustrates legacy class + file persistence nicely. Signed-off-by: https://github.com/Someshdiwan <[email protected]>
1 parent 670dddd commit 646c075

File tree

1 file changed

+13
-0
lines changed
  • Section 25 Collections Frameworks/List Interface/Vector/Stack/src

1 file changed

+13
-0
lines changed
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
98
2+
46646
3+
777
4+
788
5+
99
6+
44
7+
22
8+
45
9+
5
10+
56
11+
6
12+
67
13+
7777

0 commit comments

Comments
 (0)