Anonymous
Anonymous asked in Computers & InternetProgramming & Design · 1 month ago

java - output current line only if smaller than any other line read so far?

So I'm to create a program that reads in the input one line at a time and output the current line if and only if it is smaller than any other line read so far. When I run my program it doesn't seem to output the lines correctly and was wondering if someone could figure out what's wrong? Like I can write a really short word like 'hi' and it wouldn't output it, but it will output a longer word like 'hello.' It seems random.

I'm also required to use string compareTo() functionpublic static void doIt(BufferedReader r, PrintWriter w) throws IOException {  ArrayList<String> strings = new ArrayList<>();  String line;  boolean checkIfSmaller = true;  while((line = r.readLine()) != null) {   strings.add(line);   for (int i = 0; i < strings.size()-1; i++) {    if (line.compareTo(strings.get(i)) > 0) {     checkIfSmaller = false;    }   }      if (checkIfSmaller == true) {    w.println(line);   }   checkIfSmaller = true;  } }  

Update:

 public static void doIt(BufferedReader r, PrintWriter w) throws IOException {

  ArrayList<String> strings = new ArrayList<>();

  String line;

  boolean checkIfSmaller = true;

  while((line = r.readLine()) != null) {

   strings.add(line);

   for (int i = 0; i < strings.size()-1; i++) {

    if (line.compareTo(strings.get(i)) > 0) {

     checkIfSmaller = false;

    }

   }

   if (checkIfSmaller == true) {

    w.println(line);

   }

   checkIfSmaller = true;

  }

 }

Update 2:

sorry i fixed the format

1 Answer

Relevance
  • 1 month ago

    I don't see a reason for that strings variable.  You know that the smallest string value is the last one printed, so that's the only string you need to keep and compare to.  It's simpler, smaller and faster that way.

    As for making your idea work, it looks like it almost does already.  You need to wait until after printing the line to add it to the lines list; and set your boolean false if the new line is greater than OR EQUAL to any previous line.

         if (line.compareTo(strings.get(i)) >= 0) {

            checkIfSmaller = false;

        }

    If you're debugging with output to System.out, then while debugging you might want to flush buffers after each output line:

        if (checkIfSmaller) {

            w.println(line);

            w.flush();

        }

    That way you'll see the output right away.  It's after this if statement that you can add the  line to the strings list.  That way you won't be comparing line to itself in the inner loop.

    • Login to reply the answers
Still have questions? Get your answers by asking now.