java - 创建构造函数来读取 txt 文件

标签 java arrays text constructor

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

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

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

“ tar 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“

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

最佳答案

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

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

}

关于java - 创建构造函数来读取 txt 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20365379/

相关文章:

java.sql.BatchUpdateException : Cannot add or update a child row: a foreign key constraint fails ERROR

java - 使用 Rally api v2.0,我在查询订阅对象时无法访问工作区列表

java - 如何为 ACTION_OPEN_DOCUMENT Intent 实现自定义 MIME 类型?

javascript splice() 导致 "arrayName.splice() is not a function"错误

javascript - JQuery 动画文本

arrays - 字符串数组距离的良好指标

Java JAR 文件在不同操作系统上的行为不同

php - 如何将数组合并到Mysql中

c++ - 为什么 JSON 对象不是数组?

html - 如果它与另一个元素 (span) 共享 div,如何将 h1 的文本水平居中放置在屏幕中间