【问题标题】:Recursive StackOverflowError递归 StackOverflowError
【发布时间】:2014-02-03 08:25:43
【问题描述】:

我的目标是制作一个小程序,它接受 Scanner 输入并使用 STACK 和 RECURSION 来反转单词。

请注意,我知道如何制作一个可以做到这一点的程序。我只是无法同时使用 STACK 和 RECURSION。

例如输入“black is cat The”将输出“The cat is black”

我所拥有的会导致注释行显示的 StackOverflowError。

任何关于如何解决这个问题或做得更好的想法将不胜感激。

import java.util.*;

public class Reverse
{

    public static String wordReverse(String[] theWords) {


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

       for(String wordsHold : theWords) {
            stacker.push(wordsHold);
        } 

        while ( !stacker.empty() ){
               stacker.pop();
        }       

        return wordReverse(theWords);  // Cause of StackOverflowError
        } 

    public static void main(String args[])

    {

        Scanner takeIn = new Scanner(System.in);

        String allWords = takeIn.nextLine();

        String[] goodWords = allWords.split(" ");

        System.out.println(wordReverse(goodWords)); 

        takeIn.close(); 
    }
}

【问题讨论】:

  • 通常,您使用(显式)堆栈或递归 - 您似乎试图同时使用两者。
  • 完全同意@Blorgbeard,递归本身就是一个栈。
  • 你为什么不在你的方法中返回一个String?它永远不会结束。
  • 就像 Blorgbeard 说的那样。请注意,当您递归调用函数时,变量无论如何都会被推送到堆栈中。使用您自己的堆栈而不是 CPU 的堆栈只是一种替代方法,使用它通常不会使用递归。
  • 您需要做的就是获取stacker.pop() 的输出并将其附加到一个字符串,然后返回该字符串,而不是调用您自己。你不会使用递归,但你的函数会工作:)

标签: java recursion stack stack-overflow


【解决方案1】:

由于wordReverse() 总是调用wordReverse(theWords),所以递归永远不会结束。这将导致程序堆栈溢出。它与stacker 变量无关。巧合的是,您的无限递归方法恰好与 Stack&lt;&gt; 类一起使用。

你可以考虑像这样实现你的wordReverse()

public static String wordReverse(String[] theWords) {

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

    for (String wordsHold : theWords) {
        stacker.push(wordsHold);
    }

    String ret = "";
    while (!stacker.empty()) {
        ret = ret + stacker.pop();
    }

    return ret;
}

【讨论】:

    猜你喜欢
    • 2012-10-21
    • 1970-01-01
    • 2021-03-22
    • 1970-01-01
    • 1970-01-01
    • 2013-02-25
    • 1970-01-01
    • 1970-01-01
    • 2021-12-15
    相关资源
    最近更新 更多