为什么我的Java字符串转换器不起作用?

时间:2015-01-23 18:33:14

标签: java algorithm data-structures

我的任务是反转一个字符串。我是通过将字符串转换为char数组来完成的。然后将字符推送到堆栈或从堆栈弹出到char数组。然后我将char数组转换回字符串。这是我的代码:

public class StringReverser {

public static void main(String[] args) {

    String convertThis = "hej";
    //print out char pre convert
    System.out.println(convertThis);

    //convert here
    StringReverser strrvs = new StringReverser();
    String newConvert = strrvs.convertString(convertThis);
    //print out char post convert
    System.out.println(newConvert);
}

public String convertString (String string){


    //convert string to char array
    char[] charToConvert = string.toCharArray();
    //get number of characters
    int s = charToConvert.length;
    //create a stack
    MyStack mystack = new MyStack(s);
    //push all character in character list on stack.
    for(char character : charToConvert){
        mystack.push(character);
    }
    //get all character from stack. they are now in reversed order
    int charnumb = 0;
    while(mystack.isEmpty() != false){
        charToConvert[charnumb] = mystack.pop();
        charnumb++;
    }
    //convert character array to string
    String newString = String.valueOf(charToConvert);
    return newString;

}

private class MyStack{

    //variables for size of stack size
    private int stackSize;
    private char[] stackArray;
    private int top;

    //create the stack
    public MyStack(int s) {

        stackSize = s;
        stackArray = new char[stackSize];
        top = -1;

    }

    //method for pushing character on top of stack.
    public void push(char push) {
        stackArray[++top] = push;
    }
    //method for pop the character on top of stack.
    public char pop() {
        return stackArray[top--];
    }
    //method for getting the character on top of stack.
    public long peek() {
        return stackArray[top];
    }
    //method for checking if stack is empty.
    public boolean isEmpty() {
        return (top == -1);
    }
    //method for checking if stack is full.
    public boolean isFull() {
        return (top == stackSize - 1);
    }


}

}

2 个答案:

答案 0 :(得分:2)

while(mystack.isEmpty() != false)相当于while (mystack.isEmpty),这意味着您的循环将立即退出而不会从堆栈中弹出任何内容。

您应将其更改为:

while(!mystack.isEmpty()){
    charToConvert[charnumb] = mystack.pop();
    charnumb++;
}

答案 1 :(得分:0)

你可以只用一个StringBuilder来反转你的字符串。

new StringBuilder("AwesomeString").reverse().toString()