簡體   English   中英

我想通過將 arraylist 傳遞給 java 中的新堆棧來反向打印 arrayList

[英]I want to print the arrayList in reverse by passing the arraylist to a new stack in java

此作業要求實現printWordRun以便它打印它可以從輸入列表words的開頭找到的任何單詞 run 。 單詞 run 應該以相反的順序打印,每個單詞在一個單獨的行上。 PrintWordRun 是一個方法,它接受一個叫做words的參數,它是一個ArrayList<String> 單詞 run 是輸入列表中的一系列單詞,其中每個單詞的長度都比前一個長。 一旦我們遇到列表的末尾,或者遇到長度等於或短於前一個單詞的單詞,單詞 run 就會結束。

數組是:

一世



快樂的

坐着

結果應該是:

快樂的



一世

為了獲得這項作業的全部學分,我必須像以前一樣使用堆棧來打印它,但是我無法將“快樂”這個詞放入堆棧中。 我的輸出是:

一世



public class Program {
    private void printWordRun(ArrayList<String> words) {

        // Here is the code I Wrote. 
        Stack<String> wordRun = new Stack<>();

        for(int i = 1; i < words.size(); i++) {
            String str1 = words.get(i-1);
            String str2 = words.get(i);
            if(str2.length() < str1.length()) {
                break;
            }
            if(str1.length() < str2.length()){
                wordRun.push(str1);

            }


            System.out.println(wordRun);
        }
    }

    public static void main(String[] args) {
        Program program = new Program();
        program.testPrintWordRun();
    }

    private void testPrintWordRun() {
        ArrayList<String> words = new ArrayList<>();
        words.add("I");
        words.add("am");
        words.add("cat");
        words.add("with");
        words.add("happy");
        words.add("dog");
        words.add("sitting");

        System.out.println("Testing printWordRun...");
        printWordRun(words);
        System.out.println();
    }
}

這是構造printWordRun函數的一種方法:

Stack<String> wordRun = new Stack<>();
int maxLength = 0;

for(String s : words) {

    if(s.length() > maxLength ) {
        maxLength = s.length();
        wordRun.add(s);
    } else
        break;
}

while(!wordRun.isEmpty())
    System.out.println(wordRun.pop());

只需存儲當前最大長度的值並使用它來比較當前字符串。

輸出:

Testing printWordRun...
happy
with
cat
am
I

首先使用add(int index, E element)將單詞添加到堆棧中, add(int index, E element)最后一項作為第一個插入,如果之后條件不匹配,則中斷循環。

private void printWordRun(ArrayList<String> words) {

    // Here is the code I Wrote.
    Stack<String> wordRun = new Stack<>();

    for (int i = 1; i < words.size(); i++) {
        String str1 = words.get(i);
        String str2 = words.get(i - 1);
        wordRun.add(0, str2);
        if(str2.length() >= str1.length()) {
            break;
        }
    }

    System.out.println(wordRun); // [happy, with, cat, am, I]
}

暫無
暫無

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

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