2

I have this code to check for some largest palindrome stuff (problem)

This is part of my code:

public static void main(String[] args) throws IOException {
        BufferedWriter out = new BufferedWriter(new FileWriter("./out"));
           for(int i=999;i>0;i--)
        {
            for(int j=999;j>0;j--)
            {
                if(isPalu(i*j))
                {
                    int o=i*j;
                    out.write(String.valueOf(o));//not working
                    System.out.println(o);
                    return;
                }
            }
        }
        // out.write(String.valueOf(5*5)); //writes 25 fine!
        out.close();
    }

The ridiculous problem here is the BufferedWriter out is working outside the for loop (commented 2nd last line) and is writing to file ./out. But not inside nested loop. (I get empty file) On the other hand the println inside loop is working fine!
Also my vscode debugger is suggesting to close the out when I still having the last line for close.

Adil Saju
  • 1,101
  • 3
  • 12
  • 26
  • 4
    You never close your writer (hint: return... returns). Use the try-with-resources statement. – JB Nizet Aug 24 '19 at 14:01
  • 1
    You may want to take a look at [`try`-with-resources](https://docs.oracle.com/javase/7/docs/technotes/guides/language/try-with-resources.html). – Turing85 Aug 24 '19 at 14:02
  • Thank you very much. It worked!! @JB Nizet yeah got it i didn't close. But Any easy explanation why it donot write inside loop? – Adil Saju Aug 24 '19 at 14:13
  • 5
    It does write. But a buffered writer uses an in-memory buffer, and only writes this buffer to the underlying stream (i.e. the file) once the buffer is full, or when you flush or close the writer. That's the whole point of a buffered writer. Read the javadoc. It explains it. Always read the javadoc. – JB Nizet Aug 24 '19 at 14:18
  • @AdilSaju refer to https://docs.oracle.com/javase/8/docs/api/java/io/BufferedWriter.html. – Awan Biru Aug 24 '19 at 14:34

0 Answers0