创建构造函数以读取txt文件

时间:2013-12-04 01:55:23

标签: java arrays text constructor

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

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

txt文件包含团队的一个单词名称,后面是20个击球平均值。

“Tars 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”

我正在努力寻找如何解决这个问题并开始使用它?

4 个答案:

答案 0 :(得分:3)

我跑了这个,这可能接近你想要的。创建一个私有方法,而不是制作一个令人困惑的构造函数,构造函数将调用该方法将文件读入数组。

 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);
        }
    }

}

答案 1 :(得分:1)

好吧,如果这些都在特定文件中的一行上,那么你可以做的是构建一个bufferedreader来读取文件的第一行,根据空格拆分行,然后解析teamName和batting averages out

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]);

这些可能会抛出IOExceptions,您需要捕获它们。我认为Java 7有一种自动处理这类错误的方法(不确定这个),但由于我不熟悉Java 7的附加功能,我只是手动检查这些异常。

答案 2 :(得分:1)

您需要使用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);
        }

     }
}

希望这有帮助

答案 3 :(得分:1)

尝试使用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
}