-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?

2
  • Use a java.io.FileWriter. Commented Mar 5, 2017 at 7:38
  • 1
    Possible duplicate of Java - Writing strings to a CSV file Commented Mar 5, 2017 at 7:40

1 Answer 1

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;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.