I have tested multiple times with differing string lengths and combinations and it always prints the longest string(s) on new lines. I can't understand why it won't pass the last two conditions?
package com.codegym.task.task07.task0708;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
/*
Longest string
1. Initialize the list of strings.
2. Read 5 strings from the keyboard and add them to this list.
3. Using a loop, find the longest string in the list.
4. Display the string. If there is more than one, display each on a new line.
Requirements:
1. Initialize the Solution class's existing strings field to a new ArrayList<>.
2. The program should read 5 strings from the keyboard and write them to the list of strings.
3. The program should display the longest string.
4. If several strings qualify as the longest, then you need to display each of them on a new line.
*/
public class Solution {
private static List<String> strings;
public static void main(String[] args) throws Exception {
//write your code here
strings = new ArrayList<>();
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
for(int i = 0; i < 5; i++){
String myString = reader.readLine();
strings.add(myString);
}
int largestString = strings.get(0).length();
String largestStringText;
ArrayList<String> longestStrings = new ArrayList<>();
// Use for loop to determine longest string
for(int i = 0; i < strings.size(); i++)
{ // Test which String is the largest
if(strings.get(i).length() >= largestString)
{
largestString = strings.get(i).length();
largestStringText = strings.get(i);
longestStrings.add(largestStringText);
}
}
longestStrings.forEach(System.out::println);
}
}