我試圖讓文件讀入Arraylist
,然後從文件中讀取數字並計算平均值。我無法讀取該文件,並打開JFileChooser
。我花了三天的時間試圖讓這個工作。我在這裏看到過一些類似的問題,但沒有使用JFileChooser
。我的代碼是JFileChooser
。我知道如何計算平均值,但我只需要讀取文件中的數字。當我通過文件選擇器打開文件時,如何獲取文件以讀取Arraylist
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
public class Week07 {
static JFileChooser fileChooser = new JFileChooser();
public static void main(String[] args) throws IOException {
String theFile;
theFile = getTheFileName();
double theAverage;
theAverage = getTheAverage(theFile);
displayTheResult(theAverage,"The average is: ");
}
public static String getTheFileName() {
String status;
fileChooser.showOpenDialog(null);
status = fileChooser.getSelectedFile().getAbsolutePath(); {
return status;
}
}
private static double getTheAverage(String theFile) throws NumberFormatException, IOException{
String fileName = getTheFileName();
FileReader fr = new FileReader(theFile);
BufferedReader br = new BufferedReader(fr);
所以這裏是我有,但現在我不能讓它顯示平均值。
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
public class Week07 {
static JFileChooser chooser = new JFileChooser();
public static void main(String[] args) throws IOException {
String theFile;
theFile = getTheFileName();
double theAverage;
//theAverage = getTheAverage(theFile);
//displayTheResult(theAverage,"The average is: ");
}
public static String getTheFileName() {
String status;
chooser.showOpenDialog(null);
status = chooser.getSelectedFile().getAbsolutePath(); {
return status;
}
}
public List<String> readFile() throws IOException
{
JFileChooser chooser = new JFileChooser();
int result = chooser.showOpenDialog(null);
//check result
File theFile = chooser.getSelectedFile();
//needs exception handling etc.
BufferedReader br = new BufferedReader(new FileReader(theFile));
List<String> data = new ArrayList<String>();
String line;
while ((line = br.readLine()) != null)
data.add(line);
br.close();
return data;
}}
public static double average(List<Integer> readFile) {
if (readFile == null || readFile.isEmpty())
return 0.0;
// Calculate the summation of the elements in the list
long sum = 0;
int n = readFile.size();
// Iterating manually is faster than using an enhanced for loop.
for (int i = 0; i < n; i++)
sum += readFile.get(i);
// We don't want to perform an integer division, so the cast is mandatory.
return ((double) sum)/n;
}
}
哪裏文件讀取代碼? – HectorLector
兩個正交的問題。是否通過FileChooser選擇文件並不重要。 – merlin2011
這是帶有文件閱讀代碼的代碼。 – user3670665