Creating a constructor to read a txt file

谁说我不能喝 提交于 2019-12-25 04:56:32

问题


I am creating a program that will produces the statistics of a baseball team

i am trying to create a constructor to read the file into the teamName instance variable and the battingAverages array.

the txt file contains the one word name of the team followed by 20 batting averages.

"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 "

I am struggling to find how to go about this and get it started?


回答1:


I ran this and this might be close to what you want. Instead of making a confusing constructor, make a private method that the constructor will call to read in the file into the array.

 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:


Well, if these are all on one line in a specific file then what you could do is construct a bufferedreader to read the first line of your file, split the line based on spaces, and then parse the teamName and 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]);

These might throw IOExceptions, which you will need to catch. I think Java 7 has a method to automatically handle these kinds of errors (not sure about this), but as I am new to Java 7's added functionality, I would just manually check for those exceptions.




回答3:


You need to use the BufferedReader, FileInputStream, and InputStreamReader. Your file.txt should have the batting averages on every line, as shown below.

0.592
0.427
0.194

Here is an example of a class that when created, it will read a text file line by line and add each line to the array list:

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

     }
}

Hope this helps




回答4:


Try using the Scanner class.

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
}


来源:https://stackoverflow.com/questions/20365379/creating-a-constructor-to-read-a-txt-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!