【问题标题】:Creating a constructor to read a txt file创建一个构造函数来读取一个txt文件
【发布时间】:2013-12-04 01:55:22
【问题描述】:

我正在创建一个生成棒球队统计数据的程序

我正在尝试创建一个构造函数来将文件读入 teamName 实例变量和 battingAverages 数组。

txt 文件包含球队的单字名称,后跟 20 个击球率。

“焦油0.592 0.427 0.194 0.445 0.127 0.483 0.352 0.190 0.335 0.207 0.116 0.387 0.243 0.225 0.401 0.382 0.556 0.319 0.475 0.279”

我正在努力寻找如何去做并开始它?

【问题讨论】:

标签: java arrays text constructor


【解决方案1】:

我运行了这个,这可能接近你想要的。与其创建一个令人困惑的构造函数,不如创建一个构造函数将调用以将文件读入数组的私有方法。

 import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;



public class Baseball {

    private File textFile;
    private Scanner input;
    private String teamName;

    //this will only work if you know there will be 20 entries everytime
    //otherwise I recommend loading the data into an ArrayList
    private double []battingAvgs = new double[20];

    public Baseball(String file){
        textFile = new File(file);
        readInFile(textFile);

    }

    //private method that reads in the file into an array 
    private void readInFile(File textFile){
        try {
            input = new Scanner(textFile);

            //read first string into variable teamName
            teamName = input.next();

            int i=0;
            //iterate through rest of file adding it to an ArrayList
            while(input.hasNext()){
                battingAvgs[i] = input.nextDouble();
                i++;
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    //print out array
    public void printArray(){
        for(Double a: battingAvgs){
            System.out.println(a);
        }
    }

}

【讨论】:

    【解决方案2】:

    好吧,如果这些都在特定文件中的一行上,那么您可以做的是构建一个缓冲读取器来读取文件的第一行,根据空格分割行,然后解析 teamName 和击球平均值.

    BufferedReader br = new BufferedReader(new FileReader("myfile.txt"));
    String[] line = br.readLine().split(" ");
    br.close();
    teamName = line[0];
    battingAverages = new int[20];
    for(int i = 0; i < 20; i++)
        battingAverages[i] = Integer.parseInt(line[i+1]);
    

    这些可能会引发 IOException,您需要捕获这些异常。我认为 Java 7 有一种方法可以自动处理这些类型的错误(对此不确定),但由于我是 Java 7 新增功能的新手,所以我只会手动检查这些异常。

    【讨论】:

      【解决方案3】:

      您需要使用BufferedReaderFileInputStreamInputStreamReader。您的 file.txt 应该在每一行都有击球率,如下所示。

      0.592
      0.427
      0.194
      

      这里是一个类的例子,当它被创建时,它将逐行读取一个文本文件并将每一行添加到数组列表中:

      import java.io.BufferedReader;
      import java.io.FileInputStream;
      import java.io.InputStreamReader;
      import java.util.*;
      
      public class Class {
          ArrayList<Double> averages;
      
          public Class() {
              averages = new ArrayList<Double>();
              try {
                  FileInputStream in = new FileInputStream("inputFile.txt"); //your file path/name
                  BufferedReader br = new BufferedReader(new InputStreamReader(in));
                  String strLine;
      
                  while((strLine = br.readLine())!= null) averages.add(Double.parseDouble(strLine));
      
              }catch(Exception e){
                  System.out.println(e);
              }
      
           }
      }
      

      希望对你有帮助

      【讨论】:

        【解决方案4】:

        尝试使用Scanner 类。

        File file=new File("TestFile.txt"); //Create a new file
        Scanner scan=new Scanner(file);//Create a Scanner object (Throws FileNotFoundException)
        if(scan.hasNext())  //Check to make sure that there is actually something in the file.
        {
            String line=scan.nextLine();    //Read the line of data
            String[] array=line.split(" "); //Split line into the different parts
            teamName=array[0];  //The team name is located in the first index of the array
            battingAverages=new double[array.length-1];//Create a new array to hold the batting average values
            for(int i=0;i<battingAverages.length;i++)   //Loop through all of the averages
            {
                double average=Double.parseDouble(array[i+1]);//Convert the string object into a double
                battingAverages[i]=average; //Add the converted average to the array
            }
            System.out.print(teamName+" "+Arrays.toString(battingAverages));    //[Optional] Print out the resulting values
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-05-10
          • 2020-12-23
          • 2020-10-17
          • 2014-01-19
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多