2014-10-08 88 views
1

這裏是我的路線:如何在一個循環中讀取多個數組?

這個程序將使用兩個數組 - 這些被稱爲平行數組。你將不會使用一個對象數組。 這個應用程序中至少有6種方法(包括main())

inputData() - 從數據文件輸入到兩個數組 - 數據文件在下面,稱之爲「population.txt」 記住在將Scanner對象關聯到它之前檢查文件的存在 displayCountries() - 顯示所有國家 - 僅顯示國家

請問您爲什麼不能運行?我需要將人口和國家名稱的價值放在一起,以便我可以在稍後的表格中填寫。所以我想我需要將第一個值讀入countryName並將第一個值讀入到populationNum中,而不是同時讀入它們。我正在閱讀的文字在代碼下方。但我不知道該怎麼做。我也想知道當我實例化時是否需要[25]。它給我這個錯誤:

Exception in thread "main" java.util.NoSuchElementException: No line found 
at java.util.Scanner.nextLine(Scanner.java:1540) 
at Population.inputData(Population.java:32) 
at Population.main(Population.java:13) 

這是我的代碼:

import java.io.*; 
import java.util.Scanner; 
import java.io.IOException; 
import java.text.DecimalFormat; 

public class Population{ 
    public static void main(String [] args)throws IOException{ 
     //Arrays 
     String [] countryNames = new String [25]; 
     int [] populationNum = new int [25]; 
     //Input data from file into the array 
     inputData(countryNames, populationNum); 
     //Displays and calculations 
     displayCountries(countryNames); 
    } //end main() 

    //this class gets the input for arrays from the file 
    public static void inputData(String [] countryNames, int [] populationNum) throws IOException{ 
     File infile = new File("population.txt."); 
     int index = 0; 
     Scanner scan = new Scanner(infile); 
     while(scan.hasNext()) 
     for(int i = 0; i < countryNames.length; i++) 
     countryNames[i] = scan.nextLine(); 
     for(int i = 0; i < populationNum.length; i++) 
     populationNum[i] = scan.nextInt(); 
    } //end inputData() 
    //this class displays the countries 
    public static void displayCountries(String [] countryNames) { 
     for(int i = 0; i < countryNames.length; i++) 
     System.out.println(countryNames[i]); 
    } //end displayCountries() 
}//end class 

Ghana 
24333000 
Brazil 
193364000 
Australia 
23480970 
Nigeria 
17
Papua New Guinea 
6888000 
Mexico 
108396211 
Egypt 
79221000 
Iran 
75078000 
Myanmar 
50496000 
Belgium 
10827519 
Tuvalu 
10000 
russia 
141927297 
+0

什麼是輸入的實際格式?每個國家都在一條線上,下一條線上的人口是多少?或者是同一行上的一些數據? – ajb 2014-10-08 01:52:41

+0

是的每個輸入都在不同的行上,我有24行12個數字和12個國家名稱。 – 2014-10-08 01:56:22

回答

3

您需要閱讀到同一迴路兩個數組,像這樣:

int i = 0; 
while(scan.hasNext()) { 
    countryNames[i] = scan.nextLine(); 
    if (scan.hasNext()) populationNum[i] = scan.nextInt(); 
    if (scan.hasNext()) scan.nextLine(); // Go to the next line 
    i++; 
} 

while裏的兩個for循環是不正確的(更不用提的是,第二for循環甚至不部分while,因爲你省略了花括號)。

Demo.

+1

最後一個不應該是'scan.nextLine()'而不是'scan.next()'嗎?我認爲'scan.nextLine()'只會返回空白直到包括換行符,但'scan.next()'會吃下一個國家的名字......我可能是錯的,還沒有測試過。 – ajb 2014-10-08 01:54:55

+0

我這樣做了,並得到相同的異常錯誤 – 2014-10-08 01:57:11

+0

@AndrewMarbl你做了編輯後再試一次嗎?我試了一下,它應該是正確的,除了輸出會有很多行說「空」 - 你需要弄清楚如何處理這些。 – ajb 2014-10-08 02:01:25

0

您需要{一段時間後(scan.hasNext())和關閉}兩個for循環之後。當掃描器已經在文件末尾時,while循環掃描所有數據,然後for循環嘗試執行scan.next。希望這有助於

相關問題