0

I have this issue where my code runs fine on the latest version of java but not on my college computers because they're on an older Java API (not that old but not the latest version). Here is the code and my task:

'Write a program that takes as input a number n and a text string filename and writes n lines to the file where each line is of the form: i: sqrt(i) sqrt(i) sqrt(i). The first column ranges from 1..n whilst the first square root is to one decimal place, the second is to two decimal places and the third is to three decimal places.'

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

public class CSLab5 {
  public static void writeFile(final String filePath, final int n) throws IOException {
      String path = filePath.concat("file.txt");
           try (BufferedWriter writer = new BufferedWriter(new FileWriter(path))) {
            final String format = "%-10s %-10.1f %-10.2f %-10.3f %n";
            for(int i=1;i<=n;i++){
                final double root = Math.sqrt(i);
                writer.write(String.format(format,i+":",root ,root,root));
            }
        }
    } 
}

I am not sure how I can modify the code to compliment the code for the older version 1.6 I believe. I get errors on the try statement. thanks

Maytham Fahmi
  • 31,138
  • 14
  • 118
  • 137
Mark
  • 3
  • 1

1 Answers1

0
try (BufferedWriter writer = new BufferedWriter(new FileWriter(path)))

This is try with resource coming in 1.8. Change it so that it is working in older version.

try {
    BufferedWriter writer = new BufferedWriter(new FileWriter(path)
}

Also add a catch or finally block.

But for version problem issue is try with resource

P S M
  • 1,121
  • 12
  • 29
  • 1
    Don't forget to close the writer in a finally block – Austin Mar 10 '16 at 09:53
  • We can't close the writer in a finally block as it is declared inside try block. It gives compilation error **writer cannot be resolved** – P S M Mar 10 '16 at 09:59
  • See https://docs.oracle.com/javase/tutorial/essential/exceptions/putItTogether.html – Austin Mar 10 '16 at 10:01
  • Look carefully. There PrintWriter out is declared outside of try block.Only initialized inside try block.So out is accessible in catch block. – P S M Mar 10 '16 at 10:06
  • *Try-with-resources* was released in *Java 7* and not in *Java 8*. – cassiomolin Mar 10 '16 at 10:11
  • @PSM That's my point. You need to fix that. That *try* block needs a *finally* block to guarantee you release the `writer`'s resources. So you need to fix the scope of `writer`. http://stackoverflow.com/questions/15768645/what-is-the-benefit-to-use-finally-after-try-catch-block-in-java – Austin Mar 10 '16 at 10:14
  • should I include catch exception too...? – Mark Mar 10 '16 at 10:19