我正在尝试将文件读入Arraylist,读回文件中的数字并计算数字的平均值是文件。我尝试了几种不同类型的代码但没有成功。这是我的代码。如果有人可以请你告诉我代码有什么问题并告诉我如何解决它我会非常感激。
import java.io.BufferedReader;
import java.io.File;
//import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
//import java.io.InputStreamReader;
import java.util.ArrayList;
//import java.util.List;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
public class Week07 {
public static void main(String []args) throws IOException
{
JFileChooser chooser = new JFileChooser();
int a = chooser.showOpenDialog(null);
//check result
File file = null;
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
file = chooser.getSelectedFile();
}
return;
}
File file;
ArrayList<String> values = new ArrayList<String>();{
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String text = null;
while ((text = br.readLine()) != null) {
values.add(text);
}
} catch (IOException exp) {
exp.printStackTrace();}
JOptionPane.showMessageDialog(null, "The Numbers are :" + values);
}}
答案 0 :(得分:0)
选择文件后返回,请检查下面代码中的return
File file = null;
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
file = chooser.getSelectedFile();
}
return;
更改该代码执行此操作:
File file = null;
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
file = chooser.getSelectedFile();
}
if(file==null){
return;//only return if no file was choosed
}