【发布时间】:2014-10-08 01:41:56
【问题描述】:
这是我的方向:
这个程序将使用两个数组——它们被称为并行数组。您将不会使用对象数组。 您将在此应用程序中至少有 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
170123000
Papua New Guinea
6888000
Mexico
108396211
Egypt
79221000
Iran
75078000
Myanmar
50496000
Belgium
10827519
Tuvalu
10000
russia
141927297
【问题讨论】:
-
输入的实际格式是什么?每个国家都在一条线上,人口在下一条线上吗?还是其中一些数据在同一行?
-
是的,每个输入都在不同的行上,我有 24 行,包含 12 个数字和 12 个国家/地区名称。