gpt4 book ai didi

java - 为什么我的 Java 字符串转换器不工作?

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:58:37 26 4
gpt4 key购买 nike

我的任务是反转字符串。我是通过将字符串转换为 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);
}


}

最佳答案

while(mystack.isEmpty() != false) 等同于 while (mystack.isEmpty),这意味着您的循环将立即退出而不从堆栈。

你应该把它改成:

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

关于java - 为什么我的 Java 字符串转换器不工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28116459/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com