簡體   English   中英

我想檢查堆棧集合中的每個元素並反向打印。 打印輸出應該打印每個元素,只要它按升序排列

[英]I want check each element in the stack collection and print it in reverse. the print out should print each element as long as its in ascending order

作業是反向打印。 每個元素的尺寸都比前一個大。 所以當訂單被打亂時,它應該停止。

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

        
        for(int i = words.size() - 1; i > 0; i--) {
            String str = words.get(i);
            if(str.length() < words.size()) {
                System.out.println(str);
            }

        }
}

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

打印應該是:

我對貓很滿意嗎

我得到:

狗對貓很滿意,我是

為了檢查當前字符串的長度是否大於前一個字符串的長度,我們需要獲取前一個字符串及其長度:

if (str.length() > words.get(i-1).length())

當您使用:

if(str.length() < words.size())

您實際上是在檢查當前字符串的長度是否大於ArrayList words的大小。


此外,檢查訂單是否被打亂不應該反過來進行。 如果相反,則輸出應為:

sitting
dog

您可能希望在printWordRun創建一個新列表, printWordRun包含words所有元素,直到順序被打亂,然后反向打印。

偽代碼:

// The output always contains the first word
list reverseList (words[0]);

// start from the second word
for(word in words)
    if word.size == previous_word.size - 1 -> add word to reverse

// start from the end of reverse
for(word in reverse)
    print word

從最后一個 before 元素開始,檢查當前字符串的長度是否比下一個少 1。 如果是,打印出來。

for(int i = words.size() - 2; i >= 0; i--) {
    String str = words.get(i);
    if(str.length() ==  words.get(i + 1).length() - 1) {
         System.out.println(str);
    }
}

暫無
暫無

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

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