Java编程-栈应用(单词逆序)

来源:互联网 发布:淘宝星星等级怎么看 编辑:程序博客网 时间:2024/05/21 09:04

Reverser.java

public class Reverser {private String input;private String output;public Reverser(String in){this.input = in;}public String doRev() {int stackSize = input.length();Stack stack = new Stack(stackSize);for (int i = 0; i < stackSize; i++){char ch = input.charAt(i);stack.push(ch);}output = "";while(!stack.isEmpty()){char ch = stack.pop();output += ch;}return output;}}

测试代码

import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;public class StackDemo {/** * @param args */public static void main(String[] args) throws IOException{// TODO Auto-generated method stub//Demo1//Stack stack = new Stack(10);//stack.push('1');//stack.push('2');//stack.push('3');//stack.push('4');////while(!stack.isEmpty())//{//System.out.println(stack.pop());//}//Demo2: Reverse the wordString input, output;while(true){System.out.println("Enter a string");System.out.flush();input = getString();if (input.equals("")){break;}Reverser reverser = new Reverser(input);output = reverser.doRev();System.out.println(output);}}public static String getString() throws IOException{InputStreamReader isr = new InputStreamReader(System.in);BufferedReader br = new BufferedReader(isr);String s = br.readLine();return s;}}