【问题标题】:Why is my code only reading the first column of numbers in the .txt file in java为什么我的代码只读取java中.txt文件中的第一列数字
【发布时间】:2018-09-14 20:50:59
【问题描述】:

我正在尝试将 .txt 文件读入两个不同的数组,一个 1d 字符串数组和一个 2d int 数组。代码将名称读入 NamesArray 就好了。但是,代码似乎要么只读取第一列数字,要么只输出第一列。我不确定我的代码哪里出错了。非常感谢任何帮助!

下面的数据是它在文件中的格式。

Jason 10 15 20 25 18 20 26  
Samantha 15 18 29 16 26 20 23  
Ravi 20 26 18 29 10 12 20  
Sheila 17 20 15 26 18 25 12  
Ankit 16 8 28 20 11 25 21

这是我到目前为止的代码。

import java.io.*;
import java.util.*;

public class Page636Exercise12
{
//      static Scanner console = new Scanner(System.in); 

    public static void main(String[] args) throws FileNotFoundException, IOException
    {                                                              
        int Count = 0;

        String[] NamesArray = new String[5];
        int [][] MileageArray = new int [5][7];

        int Mileage = 0;
        String Names = "";

        //Open the input file.
        Scanner inFile = new Scanner(new FileReader("Ch9_Ex12Data.txt"));

        //Reads from file into NamesArray and MileageArray.
        while (inFile.hasNext())
        {
             Names = inFile.next();
             NamesArray[Count] = Names;
             Mileage = inFile.nextInt();
             MileageArray[Count][Count] = Mileage;
             Names = inFile.nextLine();

             System.out.println(NamesArray[Count] + " " + MileageArray[Count][Count]);                
            Count++;           
           inFile.close();           
    }
}

这是我得到的输出。

Jason 10  
Samantha 15  
Ravi 20  
Sheila 17  
Ankit 16  

【问题讨论】:

  • 注意 Java 命名约定。变量名应以小写字符开头
  • 您只获得第一个数字,因为您只存储了第一个数字 Scanner.nextInt() 获得下一个通常由空格分隔的 token (我假设它们在您的文件中)。
  • 您也可以尝试读取行,用空格分隔字符串(''),第一个元素将始终是名称,其余部分将是数字。它会让你的代码更加灵活,即使数字的数量变化它仍然可以工作。

标签: java arrays multidimensional-array java-io


【解决方案1】:

问题是您只在索引[count][count] 处的MileageArray 中存储一个数字。您将需要使用一个循环填充数组,该循环循环预期的整数标记总数,如下所示:

for(int j = 0; j < 7; j++){
    Mileage = inFile.nextInt();
    MileageArray[Count][j] = Mileage;
}
Names = inFile.nextLine();

我还建议您将MileageArray 列和行大小指定为常量。即:

final int ROWS = 5;
final int COLS = 7;

如果输入文件格式发生变化,这将允许您以更可配置的方式更新解析代码。

【讨论】:

  • 很抱歉,但这个解决方案并不是真正的问题解决方案。想想你建议inFile.nextInt() 在循环之外,所以存储在Mileage 中的值对于每次迭代都是相同的,所以基本上你存储的是第一个扫描和解析的数字的 7 倍;)
  • 你是对的。示例已更新以反映这一点。
【解决方案2】:

您只读取第一个 int 数字

Mileage = inFile.nextInt();

您需要一个内部循环运行 7 次来读取所有整数并将它们添加到二维数组中。

【讨论】:

    【解决方案3】:

    答案很简单,通过调用 Mileage = inFile.nextInt() 会得到当前所在输入行的下一个标记并将其解析为 int 但由于数字由某些东西分隔(假设为空格)仅读取和解析第一个数字。
    您有多种选择来解决此问题。您可以:

    解决方案 1

    Sparkplug were quicker than me.

    解决方案 2

    try (BufferedReader br = new BufferedReader(
            new FileReader( new File( "Performance_Results_310_13.dat" ) ) ))
        {
          String line;
          while ( (line = br.readLine()) != null )
          {
            // split everything in a temporary array
            String[] temp = line.split( "\\s" );
            // the name will always at the first position rest of the line are the numbers
            name = temp[ 0 ];
            nameArray[ count ] = name;
            // or just simply nameArray[count] = temp[0]
            // start at 1 since 0 is the name
            for ( int i = 1; i < temp.length - 1; i++ )
            {
              // create a new array which is big enough for all numbers following
              mileageArray[count] = new int[temp.length - 1];
              mileageArray[ count ][ i - 1 ] = Integer.parseInt( temp[ i ] );
            }
            count++;
          }
        }
        catch ( IOException e )
        {
          e.printStackTrace();
        }
    

    此解决方案读取整行,然后将其解析为所需的格式。我认为它更灵活一些,但您必须确保数组足够大以存储数据。另请注意,此解决方案仅在空格后的每个标记都可解析为 int(第一个除外)时才有效。

    【讨论】:

      【解决方案4】:

      您需要使用两个变量来遍历二维数组并同时打印它。您可以使用下面的代码,它可以按预期工作。

      public static void main(String[] args) throws FileNotFoundException, IOException{
                  int count = 0;
                  int j = 0;
                  String[] NamesArray = new String[5];
                  int[][] MileageArray = new int[5][7];
      
                  int Mileage = 0;
                  String Names = "";
      
                  // Open the input file.
                  Scanner inFile = new Scanner(new FileReader("Ch9_Ex12Data.txt"));
      
                  // Reads from file into NamesArray and MileageArray.
                  while (inFile.hasNext()) {
                      Names = inFile.next();
                      NamesArray[count] = Names;
                      j = 0;
                      System.out.print(NamesArray[count]);
                      while (inFile.hasNextInt())
                      {
                          Mileage = inFile.nextInt();
                          MileageArray[count][j] = Mileage;
                          System.out.print(" "+MileageArray[i][j]);
                          j++;
                      }
      
                      Names = inFile.nextLine();
                      count++;
                      System.out.println("");
                  }
                  inFile.close();
              }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-02-25
        • 1970-01-01
        • 2021-06-22
        • 2021-06-30
        • 1970-01-01
        • 1970-01-01
        • 2019-08-26
        相关资源
        最近更新 更多