1
好吧,這段代碼要求用戶輸入名稱,年份和性別,並顯示所選年份的名稱排名。它從網址讀取數據,並將其放入每年的地圖中。然後將這些映射放入數組中,最後將等級顯示給用戶。進入while循環後,我的程序從未完成運行。下面是代碼:爲什麼這個for循環在接收輸入後無限地運行? (Java)
public static void main(String[] args) throws MalformedURLException, IOException {
Scanner input = new Scanner(System.in);
Map[] boyArray = new Map[10];
Map[] girlArray = new Map[10];
System.out.print("Enter year (between 2001 and 2010): ");
String year = input.nextLine();
System.out.print("Enter gender (M or F): ");
String gender = input.nextLine();
System.out.print("Enter name: ");
String name = input.nextLine();
for (int i = 0; i < 10; i++) {
Map<String, String> boys = new HashMap<>();
Map<String, String> girls = new HashMap<>();
try {
java.net.URL url = new java.net.URL("http://www.cs.armstrong.edu/liang/data/babynamesranking"+ year + ".txt");
Scanner urlInput = new Scanner(url.openStream());
while (urlInput.hasNext()) {
String rank = input.next();
boys.put(urlInput.next(), rank);
urlInput.next();
girls.put(input.next(), rank);
urlInput.next();
}
}
catch (IOException ex) {
}
boyArray[i] = boys;
girlArray[i] = girls;
}
if (gender.charAt(0) == 'M') {
System.out.println("The name " + name + " was ranked " + boyArray[Integer.parseInt(year) - 2001].get(name) + " in " + year);
} else {
System.out.println("The name " + name + " was ranked " + girlArray[Integer.parseInt(year) - 2001].get(name) + " in " + year);
}
}
}
String rank = input.next(); < - 看起來像你想要urlInput。同樣適用於girls.put(input.next(),rank); – uthark
非常感謝你!我無法相信我沒有注意到這一點。我已經堅持了幾個小時哈哈。它現在有效! – macdaddy