我正在创建一个程序来生成棒球队的统计数据
我正在尝试创建一个构造函数来将文件读入 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/