假设我有一个文本文件,每行有两个字符串:
New York 52.523405 13.4114
San Antonio 41.387917 2.169919
Los Angeles 51.050991 13.733634
这是我将字符串从行中分离出来的代码:
for (int i = 0; i < noOfStores;i++){
nextLine = console.readLine();
nextLine = nextLine.trim();
String temp[] = nextLine.split(" ");
String Word = temp[0] + " " + temp[1];
storeNames[i] = firstWord;
latitudes[i] = Double.parseDouble(temp[2]);
longitudes[i] = Double.parseDouble(temp[3]);
}
但是如果文本文件每一行只包含一个字符串,如下所示:
Berlin 52.523405 13.4114
Barcelona 41.387917 2.169919
Dresden 51.050991 13.733634
如何在读取文本文件时检查它是否包含一个或两个字符串?
最佳答案
使用split("")
,获取返回的数组长度,然后解析数组中的最后两个String数组项,项length - 1
和length - 2
,作为 double ,然后迭代最后两项之前的剩余字符串项,并将它们组合为城市字符串。比如,
for (int i = 0; i < noOfStores;i++){
nextLine = console.readLine();
nextLine = nextLine.trim();
String temp[] = nextLine.split(" ");
int length = temp.length;
if (length < 3) {
// output is not as expected; throw some type of exception here.
}
latitudes[i] = Double.parseDouble(temp[length - 2]);
longitudes[i] = Double.parseDouble(temp[length - 1]);
// this should handle city names with 1, 2 or any number of tokens
StringBuilder wordSb = new StringBuilder();
for (int j = 0; j < length - 2; j++) {
wordSb.append(temp[j]);
if (j != length - 3) {
wordSb.append(" ");
}
}
storeNames[i] = wordSb.toString();
}
关于java - 如何检查文本文件是否包含单个字符串或两个字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32280242/