我被Java中的类型完全殴打。
我在txt文件中有坐标,最终我要格式化为这些坐标的数组,每个数组项都是双精度。
我的txt文件的每一行都是这样的:
13.716 , 6.576600074768066
目前,我试图将这一行拆分为两个字符串的数组,然后我将尝试解析为双打,但我一直在标题中得到错误。我哪里错了?
将我的字符串Arraylist转换为格式化的双坐标列表的任何其他更好的方法都会很棒,就像这样
[[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;
}
答案 0 :(得分:1)
split(",")
方法返回字符串string[]
的数组,并且不能通过字符串数组设置字符串。
包含let lan double variabels
的Crate点类,然后创建此点的数组,并用读取每一行的数据填充它们:
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;
}
答案 1 :(得分:1)
你可以像这样更新你的while循环
while ((line = reader.readLine()) != null) {
String[] splits = line.split(",");
for(String s : splits) {
data.add(s);
}
}