java简单小程序 字符串换位
发布网友
发布时间:2022-04-20 03:27
我来回答
共2个回答
热心网友
时间:2023-06-26 00:56
那就去用栈的特性,自己写一个栈类。
package reverse;
import java.util.Scanner;
import stack.StackX;;
public class ReverseApp {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while(true){
System.out.print("Enter a String:");
String value = in.nextLine();
if(value.equals("")){
System.out.println("Program is Exit");
break;
}
Reverse rev = new Reverse(value);
System.out.println("Reversed:"+rev.doRev());
}
}
}
class Reverse {
private String input;
private String output;
public Reverse(String in){
input = in;
}
public String doRev(){
int stackSize = input.length();
StackX stack = new StackX(stackSize);
for(int i = 0;i<input.length();i++){
char ch = input.charAt(i);
stack.push(ch);
}
output = "";
while(!stack.isEmpty()){
output += (char)stack.pop();
}
return output;
}
}
package stack;
public class StackX {
private int maxSize;
private int[] stackArray;
private int top;
public StackX(int s) {
maxSize = s;
stackArray = new int[maxSize];
top = -1;
}
public void push(int value) {
stackArray[++top] = value;
}
public int pop() {
return stackArray[top--];
}
public int peek() {
return stackArray[top];
}
public boolean isEmpty() {
return (top == -1);
}
public boolean isFull() {
return top == (maxSize - 1);
}
}
不好意思,弄得太复杂了。。。
其实就这样算了。。。
import java.util.Scanner;
public class TestStack {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String str = in.next();
System.out.println(str);
for(int i = str.length()-1;i>=0;i--){
char c = str.charAt(i);
System.out.print(c);
}
}
}
热心网友
时间:2023-06-26 00:57
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
System.out.println("请输入一个字符串:");
String str=scanner.next();
System.out.println(new StringBuffer(str).reverse().toString());
}
}