好的,所以此代码要求用户输入名称,年份和性别,并显示所选年份的名称排名。它从URL中读取数据并将其放入每年的地图中。然后将这些映射放入数组中,最后将排名显示给用户。进入while循环后,我的程序永远不会运行。这是代码:
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);
}
}
}
答案 0 :(得分:0)
看起来,正如@uthark已经注意到的那样,您的程序正在等待输入,因为在while
循环中,您正在等待来自System.in
的行String rank = input.next();
的输入(和行girls.put(input.next(), rank);
)。您可能打算写String rank = urlInput.next();
和girls.put(urlInput.next(), rank);
,以便排名和女孩名称来自http://www.cs.armstrong.edu/liang/data/babynamesranking
YYYY .txt
。