I have managed to display the string that occurs earlier in the list (shortest/longest) but if they is more than one string of this kind (shortest/ longest) I can't manage to save the index of the first one and display it, it just displays the last of that kind. Any thoughts would be appreciated, thanks!
package com.codegym.task.task07.task0712;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
/*
Shortest or longest
*/
public class Solution {
public static void main(String[] args) throws Exception {
//write your code here
//Create a list of strings.
ArrayList<String> strings = new ArrayList<String>();
//Add 10 strings from the keyboard.
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
for(int i = 0; i < 10; i++){
String s = reader.readLine();
strings.add(s);
}
//Find out which string occurs earlier in the list: the shortest or the longest.
//If several strings are shortest or longest, then consider the very first such string encountered.
int min = strings.get(0).length();
int max = strings.get(0).length();
for (int j = 0; j< strings.size(); j++){
if (strings.get(j).length() < min){
min = strings.get(j).length();
}
if (strings.get(j).length() > max){
max = strings.get(j).length();
}
}
int indexmin = 0;
int indexmax = 0;
for (int k = 0; k < strings.size(); k++){
if(strings.get(k).length() == min){
indexmin = strings.indexOf(strings.get(k));
}
if (strings.get(k).length() == max){
indexmax = strings.indexOf(strings.get(k));
}
}
//Display the string described in Step 3. One string should be displayed.
if (indexmin < indexmax){
System.out.println(strings.get(indexmin));
}
else
{
System.out.println(strings.get(indexmax));
}
}
}