2017-10-20 74 views
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); 
    } 

} 

}

+2

String rank = input.next(); < - 看起來像你想要urlInput。同樣適用於girls.put(input.next(),rank); – uthark

+0

非常感謝你!我無法相信我沒有注意到這一點。我已經堅持了幾個小時哈哈。它現在有效! – macdaddy

回答

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

相關問題