如何在一个循环中读取多个数组?

时间:2014-10-08 01:41:57

标签: java arrays parallels

以下是我的指示:

该程序将使用两个数组 - 这些数组称为并行数组。您将不会使用对象数组。 在此应用程序中至少有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

2 个答案:

答案 0 :(得分: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++;
}

for内的两个while循环不正确(更不用说第二个for循环甚至不是while的一部分,因为你省略了花括号)。

Demo.

答案 1 :(得分:0)

在两个for循环之后需要{after while(scan.hasNext())并关闭}。发生的事情是while循环扫描所有数据,然后当扫描程序已经在文件末尾时,for循环尝试执行scan.next。希望这有帮助