英文:
How to read first two words and last 2 words from each comma seperated line?
问题
以下是您要翻译的代码部分:
try (BufferedReader br = new BufferedReader(new InputStreamReader(file.getInputStream()))) {
// TXT文件的分隔符
String DELIMITER = ",";
// 逐行读取文件
String line;
while ((line = br.readLine()) != null) {
// 将行拆分为列
String[] columns = line.split(DELIMITER);
// 打印所有列
System.out.println("GeoData[" + String.join(", ", columns) + "]");
}
} catch (IOException ex) {
ex.printStackTrace();
}
如果您需要进一步的帮助或有其他问题,请随时提问。
英文:
I have a .txt file with following content:
NO,6549,Kristiansund,N,Møre,og,Romsdal,08,Kristiansund,1505,63.1101,7.7552
NO,6364,Vistdal,Møre,og,Romsdal,08,Molde,1506,62.7107,7.9319
NO,6365,Vistdal,Møre,og,Romsdal,08,Molde,1506,62.7107,7.9319
NO,6401,Molde,Møre,og,Romsdal,08,Molde,1506,62.7371,7.0068,4
NO,6402,Molde,Møre,og,Romsdal,08,Molde,1506,62.7371,7.0068,4
NO,6403,Molde,Møre,og,Romsdal,08,Molde,1506,62.7371,7.0068,4
NO,8502,Narvik,Nordland,09,Narvik,1806,68.4271,17.4349,4
NO,8503,Narvik,Nordland,09,Narvik,1806,68.4271,17.4349,4
NO,8504,Narvik,Nordland,09,Narvik,1806,68.4271,17.4349,4
I want to pick up the first two words from the beginning of each lines and then i also want to pick up the two last words in each lines.
What i want from the first two words is: NO
and all the numbers started with 6
, 6549
etc and 8
, 8502
etc.
But from the end of line i actually want the Latitude and Longitude, but for some lines there is 4
at the end of line. I dont want them. Any idea how I can do this? I want to create objects so i have this java object class:
public class GeoData {
private String landskode;
private String postnummer;
private String latitude;
private String longitude;
}
Following code I have until so far is:
try (BufferedReader br = new BufferedReader(new InputStreamReader(file.getInputStream()))) {
// TXT file delimiter
String DELIMITER = ",";
// read the file line by line
String line;
while ((line = br.readLine()) != null) {
// convert line into columns
String[] columns = line.split(DELIMITER);
// print all columns
System.out.println("GeoData["+ String.join(", ", columns) +"]");
}
} catch (IOException ex) {
ex.printStackTrace();
}
答案1
得分: 0
第一和第二个应该只是 columns[0]
和 columns[1]
。然后,要检查最后一个字段是否是普通的 "4",您可以使用 columns[columns.length - 1].equals("4")
。根据这是否为真或假,纬度/经度是 columns[columns.length - 3]
和 columns[columns.length - 2]
或 columns[columns.length - 1]
和 columns[columns.length - 2]
。
英文:
The first two should just be columns[0]
and columns[1]
. Then, to check whether the last field is a plain "4" you can use columns[columns.length - 1].equals("4")
. Depending on whether this is true or false, the lat/long are columns[columns.length - 3]
and columns[columns.length - 2]
or columns[columns.length - 1]
and columns[columns.length - 2]
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论