使用STACK和RECURSION从SCANNER反转单词

时间:2014-01-15 17:51:40

标签: java recursion stack

有没有办法从SCANNER获取单词并使用STACK和RECURSION反转它们?我需要这个计划中的所有三个方面。我可以单独使用Stack或单独使用Recursion执行此操作,但我无法同时使用它们。

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(); 
    }
}

1 个答案:

答案 0 :(得分:0)

递归时要记住的第一件事是定义停止条件;

public static String wordReverse(String[] theWords, Stack<String> stack) {
    // stop on null.
    if (theWords == null) {
        return null;
    } else if (theWords.length < 2) {
        // stop if there are fewer then two words.
        return theWords[0];
    }
    // push the first word.
    stack.push(theWords[0]);
    // copy the sub-array.
    String[] s = new String[theWords.length - 1];
    System.arraycopy(theWords, 1, s, 0, theWords.length - 1);
    // recurse
    return wordReverse(s, stack) + " " + stack.pop();
}

public static String wordReverse(String[] theWords) {
    // call the recursive implementation with a new Stack.
    return wordReverse(theWords, new Stack<String>());
}

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();
}

像这样工作

Hello world, goodbye world
world goodbye world, Hello