gpt4 book ai didi

java - 不兼容的类型 : String[] cannot be converted to String

转载 作者:行者123 更新时间:2023-12-02 02:12:33 25 4
gpt4 key购买 nike

我完全被 Java 中的类型打败了。

我在一个 txt 文件中有坐标,最终我想将其格式化为这些坐标的数组,每个数组项都是 double 型。

我的 txt 文件的每一行如下所示:

13.716              , 6.576600074768066  

目前,我正在尝试将这一行拆分为两个字符串的数组,然后尝试将其解析为 double ,但我不断收到标题中的错误。我哪里出错了?

将字符串数组列表转换为双坐标格式化列表的任何其他更好的方法都会很棒,就像这样

[[0,1], [0,2], 0,4]

代码:

 public static String[] getFileContents(String path) throws FileNotFoundException, IOException
{
InputStream in = new FileInputStream(new File(path));
BufferedReader reader = new BufferedReader(new InputStreamReader(in));

List<String> data = new ArrayList<String>();
StringBuilder out = new StringBuilder();
String line;
// Skips 1376 characters before accessing data
reader.skip(1378);
while ((line = reader.readLine()) != null) {
data.add(line);
// System.out.println(line);
}

for (int i=0; i < data.size(); i++){
data.set(i, data.get(i).split(","));
}
// String[] dataArr = data.toArray(new String[data.size()]);
// Test that dataArr[0] is correct
// System.out.println(data.size());
// List<String> formattedData = new ArrayList<String>();
// for (int i = 0; i < data.size(); i++){
// formattedData.add(dataArr[i].split(","));
// }
reader.close();
return dataArr;
}

最佳答案

split(",") 方法返回字符串数组 string[],并且不能逐个字符串数组设置字符串。

使用let lan double variabels创建点类,然后创建该点的数组,并用读取每行的数据填充它们:

class Point{
double lat;
double len;
Point(double lat, double len){
this.lat = lat;
this.len = len;
}
}

然后在代码中使用此类:

 public static String[] getFileContents(String path) throws FileNotFoundException, IOException
{
InputStream in = new FileInputStream(new File(path));
BufferedReader reader = new BufferedReader(new InputStreamReader(in));

List<String> data = new ArrayList<String>();
StringBuilder out = new StringBuilder();
String line;
// Skips 1376 characters before accessing data
reader.skip(1378);
while ((line = reader.readLine()) != null) {
data.add(line);
// System.out.println(line);
}
List<Point> points = new ArrayList<Point>();
for (int i=0; i < data.size(); i++){
double lat = Double.parseDouble(data.get(i).split(",")[0]);

double len = Double.parseDouble(data.get(i).split(",")[1]);
points.add(new Point(lat, len));
//data.set(i, data.get(i).split(","));
}
// String[] dataArr = data.toArray(new String[data.size()]);
// Test that dataArr[0] is correct
// System.out.println(data.size());
// List<String> formattedData = new ArrayList<String>();
// for (int i = 0; i < data.size(); i++){
// formattedData.add(dataArr[i].split(","));
// }
reader.close();
return dataArr;
}

关于java - 不兼容的类型 : String[] cannot be converted to String,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49786611/

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