最近我开始学习计算机科学课程,旨在更好地理解编程,但是在ArrayList实验中遇到了困难。该程序的目的是将x个字符串放入ArrayList中,然后按降序输出结果。
例如:Zebra, Deer, Giraffe Deer
结果:Giraffe,Zebra,Deer
我在网上找到了一些使用ArrayList比较器的示例,但我们的教授希望我们通过过滤最大的单词、打印它、删除它,然后继续循环直到所有单词都被打印出来。
以下是我的代码:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int length = 0;
String longest = "";
String currentWord = "";
ArrayList <String> DescendArray = new ArrayList<String>();
System.out.println("What would you like to add to the list?");
String userInput = input.next();
while(!userInput.equals("d"))
{
DescendArray.add(userInput);
userInput = input.next();
}
for (int i=0; i < DescendArray.size(); i++)
{
if (DescendArray.get(i).length() > longest.length())
{
currentWord = DescendArray.get(i);
if (currentWord.length() > longest.length())
{
longest = currentWord;
length = longest.length();
}
}
for (int j=1; j < DescendArray.size() -1 ; j++)
{
if (DescendArray.get(j - 1).length() > longest.length())
{
DescendArray.remove(j - 1);
}
System.out.println(longest + " " + length);
}
}
}
我猜测我的错误出现在内部循环中,但无论我使用多少不同的变化,都无法使它正常工作。