Commit 670dddd
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 861a4d6 commit 670dddd
File tree
1 file changed
+8
-10
lines changed- Section 25 Collections Frameworks/List Interface/Vector/Stack/src
1 file changed
+8
-10
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
1 | | - | |
2 | | - | |
3 | 1 | | |
4 | 2 | | |
5 | 3 | | |
6 | 4 | | |
7 | 5 | | |
8 | 6 | | |
9 | | - | |
| 7 | + | |
10 | 8 | | |
11 | 9 | | |
| 10 | + | |
| 11 | + | |
12 | 12 | | |
13 | | - | |
| 13 | + | |
14 | 14 | | |
15 | 15 | | |
16 | 16 | | |
| |||
22 | 22 | | |
23 | 23 | | |
24 | 24 | | |
25 | | - | |
| 25 | + | |
26 | 26 | | |
27 | 27 | | |
28 | 28 | | |
29 | 29 | | |
30 | | - | |
31 | | - | |
32 | | - | |
33 | | - | |
| 30 | + | |
| 31 | + | |
34 | 32 | | |
35 | 33 | | |
36 | 34 | | |
37 | 35 | | |
38 | 36 | | |
39 | 37 | | |
40 | 38 | | |
41 | | - | |
| 39 | + | |
0 commit comments