繁体   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