StackX类
public class StackX{
private int maxSize;
private char StackArray[];
private int top;
public StackX(int max){ //构造函数的定义
maxSize=max;
StackArray=new char[maxSize];
top=-1;
}
public void push(char j){ //字符压栈
StackArray[++top]=j;
}
public char pop(){ //字符弹出
return StackArray[top--];
}
public char seek(){ //查找
return StackArray[top];
}
public boolean isEmpty() //空栈判断
{
return top==-1;
}
}
Reverse反转类
public class Reverse{
private String input;
private String output;
public Reverse(String in){ //构造函数
input=in;
}
public String doRev(){ //反转功能函数 返回值为String
int stackSize=input.length();
StackX theStack=new StackX(stackSize);
for(int i=0;i<input.length();i++) //将输入的字符串压栈处理
{
char ch=input.charAt(i);
theStack.push(ch);
}
output="";
while(!theStack.isEmpty()){ //将栈中的字符逐一弹出,并被ouput接收,达到反转效果
char c=theStack.pop();
output+=c;
}
return output;
}
}
主函数,测试函数
import java.io.*; //输入流头文件
public class ReseverApp {
public static void main(String []args) throws IOException{ //函数内含有IO输入流,不处理异常就要向上抛异常
String input,output;
while(true){ //输入多组数据
System.out.println("Enter a String ");
System.out.flush(); //清空缓存区
input=getString(); //调用输入流方法↓
if(input.equals("")) break;
Reverse rv=new Reverse(input);
output=rv.doRev();
System.out.println(output);
}
}
public static String getString ()throws IOException{ //输入流方法
InputStreamReader isr=new InputStreamReader(System.in); //用InputStreamReader声明接收器,从System.in(即控制台)输入
BufferedReader br=new BufferedReader(isr); //用BufferedReader包装InputStreamReader
String s=br.readLine(); //调用BufferedReader的readLine()方法进行读取字符串
return s;
}
}
系统自带的反转函数
public class Demo {
public static void main(String []args){
StringBuilder sb=new StringBuilder("中华人民共和国");
System.out.println(sb.reverse());
}
}