gpt4 book ai didi

java - 读取文件并添加到二维 double 组中

转载 作者:行者123 更新时间:2023-12-01 17:50:36 25 4
gpt4 key购买 nike

我试图读取一个充满坐标的文件,然后将所有内容放入双二维数组中。当我运行代码时,我收到异常错误。现在已经尝试读取该文件几个小时了(我是java新手)

            Scanner input = new Scanner(new File(filename));
int row=0;
int col=0;
int rwn=0;
String[] line= new String[rwn];
while(input.hasNextLine()) {
line = input.nextLine().split(" ");//spliting 1
rwn++;
}
double[][] arrayOfEarth = new double[rwn][];//creating array for pairs
//itterating array ^ of splitting 1
for (int i=0;i<rwn;i++){
String[] ln =line[i].split(",");

double a= Double.parseDouble(ln[0]);
double b=Double.parseDouble(ln[1]);
double[] val={a,b};//adding the a and b doubles out of string to the value
arrayOfEarth[i]=val;//add arr to arr of arr
}
for (double[] c:arrayOfEarth){
System.out.println(String.format("%.0f and %.2f",c[0],c[1]));
}
}

catch (Exception e) {
System.out.println("Error bruh: "); e.printStackTrace();
}```

最佳答案

你的代码让我有点困惑。

但是你可以尝试这个:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;

public class App {

public static void main(String[] args) {
// Define sample data
String coord = ""
+ "0 90 -4228\n"
+ "0.166666666667 90 -4228\n"
+ "0.333333333333 90 -4228\n"
+ "0.5 90 -4228\n"
+ "0.666666666667 90 -4228";
Scanner input = new Scanner(coord);
int rwn = 0;
// Define a 'arrayOfEarth' as list
ArrayList<Double[]> arrayOfEarth = new ArrayList<>();
while (input.hasNextLine()) {
++rwn;
String[] line = input.nextLine().split(" ");
if (line.length == 0) {
continue;
}
arrayOfEarth.add(parseLine(line, rwn));
}
arrayOfEarth.stream()
.forEach(v -> System.out.println(Arrays.toString(v) + "\n"));

}

private static Double[] parseLine(String[] line, int row) {
if (line.length != 3) {
throw new IllegalArgumentException("Missing valiues in line " + row);
}
Double[] doubles = new Double[3];
for (int i = 0; i < 3; i++) {
try {
doubles[i] = Double.parseDouble(line[i]);
} catch (NumberFormatException e) {
throw new NumberFormatException("NAN in " + row + "/" + i + ". value: " + line[i]);
}
}
return doubles;
}
}

这不是“干净”的代码 - 只是一个示例。我已经使用了 Stream-API。如果您使用 Java 版本 < 8,则必须使用传统的 for 循环重写它。

关于java - 读取文件并添加到二维 double 组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60802287/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com