這裏是我的路線:如何在一個循環中讀取多個數組?
這個程序將使用兩個數組 - 這些被稱爲平行數組。你將不會使用一個對象數組。 這個應用程序中至少有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
什麼是輸入的實際格式?每個國家都在一條線上,下一條線上的人口是多少?或者是同一行上的一些數據? – ajb 2014-10-08 01:52:41
是的每個輸入都在不同的行上,我有24行12個數字和12個國家名稱。 – 2014-10-08 01:56:22