I've recently begun taking a Computer Science course to understand programming more and seem to have hit a roadblock with our lab on ArrayLists. The purpose of the program is to put x amount of strings into an ArrayList and then output the results in descending order.
Ex:Zebra, Deer, Giraffe Deer
Result:Giraffe, Zebra, Deer
I've looked around online and found a few examples using ArrayList comparators but our professor wants us to do it by filtering out the largest word, printing it, removing it and then continue that loop until all words are printed out.
Here is my code so far:
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);
}
}
}
}
I'm assuming my error is somewhere in the inner loop but I can't seem to get it to work no matter how many different variations I use.
Try this, it works for me.
List<String> sorted = list.stream()
.sorted(Comparator.comparingInt(String::length))
.collect(Collectors.toList());
This is basically what you gotta do:
public class Zoo {
public static void main(String[] args) {
List<String> zoo = new ArrayList<String>();
zoo.add("Zebra");
zoo.add("Deer");
zoo.add("Giraffe");
zoo.add("Deer");
while(!zoo.isEmpty()) {
String bigger = "";
for(String animal : zoo) {
if(animal.length() > bigger.length()) {
bigger = animal;
}
}
System.out.println(bigger);
while(zoo.contains(bigger)) {
zoo.remove(bigger);
}
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With