forked from biblelamp/JavaExercises
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreverse.java
More file actions
90 lines (77 loc) · 2.93 KB
/
Copy pathreverse.java
File metadata and controls
90 lines (77 loc) · 2.93 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
/**
* Book: Data Structures and Algorithms in Java, by Robert LaFore
* Chapter 4:
* reverse.java
* stack used to reverse a string
* to compile this code: javac reverse.java
* to run this program: java ReverseApp
*/
import java.io.*; // for I/O
class StackX {
private int maxSize; // size of stack array
private char[] stackArray;
private int top; // top of stack
public StackX(int s) { // constructor
maxSize = s; // set array size
stackArray = new char[maxSize]; // create array
top = -1; // no items yet
}
public void push(char j) { // put item on top of stack
stackArray[++top] = j; // increment top, insert item
}
public char pop() { // take item from top of stack
return stackArray[top--]; // access item, decrement top
}
public char peek() { // peek at top of stack
return stackArray[top];
}
public boolean isEmpty() { // true if stack is empty
return (top == -1);
}
public boolean isFull() { // true if stack is full
return (top == maxSize-1);
}
} // end class StackX
class Reverser {
private String input; // input string
private String output; // output string
public Reverser(String in) { // constructor
input = in;
}
public String doRev() { // reverse the string
int stackSize = input.length(); // get max stack size
StackX theStack = new StackX(stackSize); // make stack
for (int j=0; j<input.length(); j++) {
char ch = input.charAt(j); // get a char from input
theStack.push(ch); // push it
}
output = "";
while (!theStack.isEmpty()) {
char ch = theStack.pop(); // pop a char,
output = output + ch; // append to output
}
return output;
} // end doRev()
} // end class Reverser
class ReverseApp {
public static void main(String[] args) throws IOException {
String input, output;
while(true) {
System.out.print("Enter a string: ");
System.out.flush();
input = getString(); // read a string from kbd
if(input.equals("")) // quit if [Enter]
break;
// make a Reverser
Reverser theReverser = new Reverser(input);
output = theReverser.doRev(); // use it
System.out.println("Reversed: " + output);
} // end while
} // end main()
public static String getString() throws IOException {
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
String s = br.readLine();
return s;
}
} // end class ReverseApp