簡體   English   中英

遞歸StackOverflowError

[英]Recursive StackOverflowError

我的目標是制作一個小的程序,該程序需要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(); 
    }
}

由於wordReverse()始終調用wordReverse(theWords) ,因此遞歸永遠不會結束。 這將導致程序堆棧溢出。 它與stacker變量無關。 碰巧您的無限遞歸方法恰好與Stack<>類一起使用。

您可以考慮像這樣實現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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM