2017-03-05 55 views
-1

返回一個CSV文件中的java我要實現我所爲以下實施digitSquareSum()方法:使用「公共文件」

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; 
    } 
} 

現在,我要讓這將返回的方法與digitSquareSum填充1-500具有以下格式的CSV文件的Java文件對象:

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

所以文件應該看起來像
1,1
2,4


500,25

我該如何解決這個問題?

+0

使用'java.io.FileWriter'。 – Jeremy

+1

[Java - 將字符串寫入CSV文件]的可能重複(http://stackoverflow.com/questions/30073980/java-writing-strings-to-a-csv-file) – nandu

回答

0

在這裏你去:

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; 
}