gpt4 book ai didi

Java从栈中返回一个字符串

转载 作者:行者123 更新时间:2023-12-01 13:27:08 25 4
gpt4 key购买 nike

我应该使用一个辅助方法来反转句子中的各个单词,该方法将字符串作为参数并返回一个字符串。堆栈应该位于辅助方法中。所以我的程序可以正确反转单词。但反向实际上并没有返回,我认为它只是打印堆栈。谁能帮我返回并打印字符串变量“reverse”。

import java.util.Scanner;
import java.util.Stack;

public class ReverseStack
{
public static void main(String[] args)
{
String sentence;

System.out.print("Enter a sentence: ");
Scanner scan = new Scanner(System.in);

sentence = scan.nextLine();

System.out.println("Reversed:" + PrintStack(sentence));
}

private static String PrintStack(String sentence)
{
String reverse = "";
String next = "";

Stack<String> stack= new Stack<String>();

String words[] = sentence.split(" ");

for(int j = 1; j<words.length +1; j++)
{
String newWord = words[words.length - j]; // Single word

for(int i = 0; i < newWord.length(); i++)
{
next = newWord.substring(i,i+1);
stack.push(next);
}
stack.push(" ");
}
while(!stack.isEmpty())
{
reverse += stack.pop();
}
return reverse;
}
}

最佳答案

您反转了两次,最终得到了相同的顺序。您的堆栈给出了相反的顺序,但您以相反的顺序添加单词,因此顺序不变。

如果您使用了调试器,您应该很清楚问题是什么。

顺便说一句,您可以使代码更短。

private static String printStack(String sentence) {
Stack<String> stack= new Stack<String>();
for(String word: sentence.split(" ")
stack.push(word);
String line = stack.pop();
while(!stack.isEmpty())
line += " " + stack.pop();
return line;
}

关于Java从栈中返回一个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21757527/

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