您无法迭代到第二行,因为您在第一次迭代后返回,而不管它是否找到该国。
我建议从else条件中删除return
语句。
我还使用了一个boolean
变量,一旦找到国家就会设置该变量,并且No country found
消息只有在该国家不在列表中时才会显示。
import java.io.IOException;
import java.net.URL;
import java.util.Scanner;
public class CountryName {
public static void main(final String[] args) throws IOException {
final String address = "https://www.cia.gov/library/publications/the-world-factbook/rankorder/rawdata_2151.txt";
final URL pageLocation = new URL(address);
final Scanner in1 = new Scanner(pageLocation.openStream());
final Scanner in = new Scanner(System.in);
boolean found = false;
String line;
System.out
.print("Please enter the name of the country you would like to see the mobile users for: ");
final String country = in.next();
while (in1.hasNextLine()) {
line = in1.nextLine();
final String[] data = line.split("\t");
if (data[1].contains(country) == true) {
System.out.println("Country name: " + data[1]);
System.out.println("Mobile phone subscribers: " + data[2]);
found = true;
return;
}
}
if (!found) {
System.out.println("No Country Found");
}
in.close();
in1.close();
}
}
在其他的注意,如果你想使用集合你的程序将变得更加简洁易读。这是与HashMap
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class CountryName {
public static void main(final String[] args) throws IOException {
final String address = "https://www.cia.gov/library/publications/the-world-factbook/rankorder/rawdata_2151.txt";
final URL pageLocation = new URL(address);
final Scanner in1 = new Scanner(pageLocation.openStream());
final Scanner in = new Scanner(System.in);
final Map<String, String> countryMap = new HashMap<String, String>();
while (in1.hasNextLine()) {
final String[] line = in1.nextLine().split("\t");
countryMap.put(line[1], line[2]);
}
System.out.print("Please enter the name of the country you would like to see the mobile users for: ");
final String country = in.next();
if (countryMap.containsKey(country)) {
System.out.println("Country Name: " + country);
System.out.println("Mobile phone subscribers: "+ countryMap.get(country));
} else {
System.out.println("No Country found with that name");
}
in.close();
in1.close();
}
}
33秒相同的逻辑,你会成为答案。非常感谢你,我不敢相信我没有想到这一点。 – usernolongerregistered
@Agony没问题。花了我不到一分钟的时间来找到我的'调试器'问题。如果你打算在将来编程更多,我强烈建议你学会使用一个。 – Tdorno
我一定要看看它。我一直坐在这里看大约3个小时。我几乎秃顶了我拔出的头发:P – usernolongerregistered