-1

I have to implement a digitSquareSum() method which I have implemented as the following:

 public int digitSquareSum(int n) {
    int total;
    if (n < 10) {
        total = (int) Math.pow(n, 2);
        return total;
     } else {
        total = (int) ((Math.pow((n %10), 2)) + digitSquareSum(n/10));
        return total;
     }
}

Now, I want to make a method which will return a Java File object for a CSV file populated with digitSquareSum from 1-500 with the following format:

public File questionOne() throws Exception {
    //code here
}

So the file should look like
1,1
2,4
.
.
500,25

How do I approach this problem?

Jeremy
  • 22,188
  • 4
  • 68
  • 81

1 Answers1

2

Here you go :

public File questionOne() throws Exception {
    File file = new File("C:\\your\\path\\here", "your_file_name.csv");
    if (!file.exists()) {
        file.createNewFile();
    }
    BufferedWriter bw = new BufferedWriter(new FileWriter(file));
    for (int i = 1; i <= 500; i++) {
        bw.append(i + "," + digitSquareSum(i) + "\n");
    }
    bw.close();
    return file;
}
Anand Undavia
  • 3,493
  • 5
  • 19
  • 33