Hey guys. I'm a little bit confused. In my mind, this program should be working. But it is not passing the last verification. Can someone please tell me what I am doing wrong??
public static String compare (ArrayList<String> original) {
ArrayList<String> sorted = sord(original);
int min = 0, max = 0;
String shortest = sorted.get(0), longest = sorted.get(sorted.size() -1);
for (int i = 0; i < original.size(); i++) {
if (original.get(i).length() == shortest.length()) {
min = i;
break;
}
}
for (int j = 0; j < original.size(); j++) {
if (original.get(j).length() == longest.length()) {
max = j;
break;
}
}
String result = (min < max) ? original.get(min) : original.get(max);
return result;
}
}
package com.codegym.task.task07.task0712;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Comparator;
/*
Shortest or longest
1. Create two ArrayList "sorted" and "entered". And a String "first".
2. Read 10 elements from console and add them to "entered".
4. "first" is equal to the result of the function "compared".
*/
public class Solution {
public static void main(String[] args) throws Exception {
ArrayList<String> entered = new ArrayList<String>();
String first;
BufferedReader reader = new BufferedReader (new InputStreamReader(System.in));
for (int i = 0; i < 10; i++) {
entered.add(reader.readLine());
}
first = compare(entered);
System.out.println(first);
}
/*
Function sort receives any ArrayList of integers. Compares every element starting from one, with the one
before. If it is smaller, swaps them. Else check next.
*/
public static ArrayList sord (ArrayList<String> list) {
for(int i = 0; i < list.size(); i++) {
for(int j = 1; j < list.size() - i - 1; j++) {
if (list.get(j).length() < list.get(j-1).length()){
String temp = list.get(j);
list.set(j, list.get(j-1));
list.set(j-1, temp);
}
}
}
return list;
}
/*
Function compare takes an ArrayList and orders it by string lenght into a new one. Then creates two integer
variables "min" and "max". Compares all the elements inside the original list, to the first element on the ordered
one. If the values are the same, saves the index of the compared element to "min". Else compares it to the last
element on the ordered list. If equal values, index is saved to "max".
*/
public static String compare (ArrayList<String> original) {
ArrayList<String> sorted = sord(original);
int min = 0, max = 0;
String shortest = sorted.get(0), longest = sorted.get(sorted.size() -1);
for (int i = 0; i < original.size(); i++) {
if (original.get(i).length() == shortest.length()) {
min = i;
break;
}
}
for (int j = 0; j < original.size(); j++) {
if (original.get(j).length() == longest.length()) {
max = j;
break;
}
}
String result = (min < max) ? original.get(min) : original.get(max);
return result;
}
}