请我想调整这段从文件中读取整数的代码。 我希望代码能够检测数据集的数量 (n),而不必像下面那样手动输入数字 (4000)
双[]高=新双[4000];
public class Extracto {
public static void main(String[] args) throws IOException {
File fil = new File("C:\\Users\\Desktop\\kaycee2.csv");
FileReader inputFil = new FileReader(fil);
BufferedReader in = new BufferedReader(inputFil);
double[] tall = new double[4000];
String s = in.readLine();
int i = 0;
while (s != null) {
// Skip empty lines.
s = s.trim();
if (s.length() == 0) {
continue;
}
tall[i] = Double.parseDouble(s); // This is line 19.
// System.out.println(tall[i]);
s = in.readLine();
i++;
}
我希望调整后的代码能够获取数据长度,而无需像下面的代码所示的 4000 长度那样手动将其放入。
双[]高=新双[4000];
最佳答案
正如 Thomas 提到的,使用列表而不是数组。
File fil = new File("C:\\Users\\Desktop\\kaycee2.csv");
FileReader inputFil = new FileReader(fil);
BufferedReader in = new BufferedReader(inputFil);
ArrayList<Double> tall = new ArrayList<>();
while(in.ready()){
String s = in.readLine().trim();
if(!s.isEmpty()){
tall.add(Double.parseDouble(s);
}
}
如果您使用列表,您的代码可以进一步压缩。 当读取的字符串不是数字时,还请在事件中添加 try-catch。
关于java - 从文件中读取数据,无需手动输入数组的长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57661451/