【发布时间】:2021-09-04 08:16:18
【问题描述】:
这个任务要求实现printWordRun,以便它打印从输入列表words的开头开始它可以找到的任何单词。单词 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();
}
}
【问题讨论】:
-
哦,我忘了添加代码。刚刚编辑了原帖
标签: java arraylist data-structures collections stack