就是IO那一段还没学到。
之前的PUCH,POP,STRING和CHAR的关系搞得懂了。
学到一个定位STRING当中CHAR的转换函数。
char = String.charAt(x)
1 import java.io.*; 2 3 4 class stackString 5 { 6 private int maxSize; 7 private char[] stackX; 8 private int top; 9 10 public stackString(int s) 11 { 12 maxSize = s; 13 stackX = new char[maxSize]; 14 top = -1; 15 } 16 public void push(char j) 17 { 18 stackX[++top] = j; 19 } 20 public char pop() 21 { 22 return stackX[top--]; 23 } 24 public char peek() 25 { 26 return stackX[top]; 27 } 28 public boolean isEmpty() 29 { 30 return (top == -1); 31 } 32 public boolean isFull() 33 { 34 return (top == maxSize - 1); 35 } 36 } 37 class Reverser 38 { 39 private String input; 40 private String output; 41 42 public Reverser(String in) 43 { 44 input = in; 45 } 46 public String doRev() 47 { 48 int stackSize = input.length(); 49 stackString stackStringRev = new stackString(stackSize); 50 51 for(int i = 0; i < stackSize; i++) 52 { 53 char charInString = input.charAt(i); 54 stackStringRev.push(charInString); 55 } 56 output = ""; 57 while(!stackStringRev.isEmpty()) 58 { 59 char ch = stackStringRev.pop(); 60 output = output + ch; 61 } 62 return output; 63 64 } 65 66 } 67 public class StackApp { 68 69 /** 70 * @param args 71 */ 72 public static void main(String[] args) throws IOException { 73 // TODO Auto-generated method stub 74 String input, output; 75 76 while(true) 77 { 78 System.out.print("Enter a string: "); 79 System.out.flush(); 80 input = getString(); 81 if(input.equals("")) 82 break; 83 84 Reverser testStringRev = new Reverser(input); 85 output = testStringRev.doRev(); 86 System.out.println("Reversed : " + output); 87 88 89 } 90 91 } 92 public static String getString() throws IOException 93 { 94 InputStreamReader isr = new InputStreamReader(System.in); 95 BufferedReader br = new BufferedReader(isr); 96 String s = br.readLine(); 97 return s; 98 99 } 100 101 }
时间: 2024-11-06 07:15:16