So I'm trying to create a program that reads in user input and outputs the current line only if it is smaller than some previous line. My program works fine but it keeps printing the first line I input which shouldn't be valid because there is no other line to compare it to yet.
I was wondering if there is a way for the program to consider the first line but not output it to the user? Thanks for any help!
public static void doIt(BufferedReader r, PrintWriter w) throws IOException {
ArrayList<String> strings = new ArrayList<>();
String line;
while((line = r.readLine()) != null) {
boolean checkIfSmaller = true;
strings.add(line);
for (int i = 0; i < strings.size()-1; i++) {
if (line.compareTo(strings.get(i)) >= 0) {
checkIfSmaller = false;
}
}
if (checkIfSmaller) {
w.println(line);
}
}
}
The idea is do add the line to the list after checking for smaller lines, since it doesn't make sense to compare a line to itself. Also, the compare you make is not right IMO:
public static void doIt(BufferedReader r, PrintWriter w) throws IOException {
ArrayList<String> strings = new ArrayList<>();
String line;
while((line = r.readLine()) != null) {
boolean isSmaller = false;
for (int i = 0; i < strings.size()-1; i++) {
if (line.compareTo(strings.get(i)) < 0) {
isSmaller = true;
break;
}
}
strings.add(line);
if (isSmaller) {
w.println(line);
}
}
}