您無法迭代到第二行,因爲您在第一次迭代後返回,而不管它是否找到該國。
我建議從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