堆栈类可能是问题所在。我的堆栈类如下所示。
public class Stack
{
public static int maxSize; // size of stack array
public static char[] stackArray;
public static int top; // top of stack
/**
* Constructor for objects of class Stack
*/
public Stack(String str)
{
maxSize = 10; // set array size
stackArray = new char[maxSize]; // create array
top = -1; // no items yet
}
/**
* An example of a method - replace this comment with your own
*
* @param y a sample parameter for a method
* @return the sum of x and y
*/
public static void push(char j)
{
top++;
stackArray[top] = j; // increment top, insert item
}
public static char pop()
{
return stackArray[top--]; //access item, decrement top
}
public static boolean isEmpty()
{
return (top == -1);
}
}
我的主要方法也如下所示。
public static void main()
{
Scanner scanner = new Scanner(System.in);
String str = "";
Stack stack = new Stack(str);
System.out.println("Enter a string to be reversed: ");
str = scanner.nextLine();
for (int i=0;i<str.length();i++){
stack.push(str.charAt(i));
}
String strrev = "";
while(!stack.isEmpty()){
strrev += stack.pop();
}
System.out.println("Reverse of the string \"" + str + "\" is: \"" + strrev + "\"");
}
}
问题是,每次我运行程序时,它不会输出 hello 的相反内容,而是输出数字 111108108101104。我认为 pop() 方法是错误的
最佳答案
按如下方式更改流行音乐将解决您的问题。您应该返回一个 char 而不是 long。
public static char pop()
{
return stackArray[top--]; //access item, decrement top
}
关于java - 使用 pop 和 push 反转字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20271845/