gpt4 book ai didi

java - 使用类读取txt文件

转载 作者:行者123 更新时间:2023-12-01 13:46:04 24 4
gpt4 key购买 nike

我现在正在努力创建我的类(class)文件,我有一个 txt 文件,其中包含团队名称,后跟 20 个击球平均值。

更新:我相信我已经从 txt 文件中读取了球队名称,现在我缺少读取击球率

文本文件:

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

这是我到目前为止的代码如果您对缺少的内容或可以做不同的事情有意见,请帮助:

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

public class BaseballStats {

private String fileName;
private String teamName;
private double [] battingAverage;


public BaseballStats ( String fileName )
{
this.fileName = fileName;
boolean firstLine = true;
Scanner input = new Scanner(fileName);
while (input.hasNextLine()) {
String line = input.nextLine();
if (firstLine)
{
setTeamName (line);
firstLine = false;
continue;
}
int i=0;
while(input.hasNext())
{
battingAverage[i] = input.nextDouble();
i++;
}
}
public String getTeamName( )
{
return teamName;
}

public void setTeamName( String newTeamName )
{
teamName=newTeamName;
}

public double findMaxAverage( )
{
double max =battingAverage[0];
for ( int i =1; i < battingAverage.length; i++)
{
if(battingAverage[i] >max)
max= battingAverage[i];
}
return max;
}
public double findMinAverage( )
{
double min =battingAverage[0];
for ( int i =1; i < battingAverage.length; i++)
{
if(battingAverage[i] < min)
min= battingAverage[i];
}
return min;
}
public double spread( )
{
//returns the difference between the highest and lowest batting averages
}
public int goodPlayers( )
{
//returns the number of players with an average higher than .300
}
public String toString( )
{
// returns a String containing the team name followed by all the batting averages formatted to three decimal places.
}
}

最佳答案

这里有一个提示。

对于最大和最小平均值,您将需要一个类变量来保存这些值。

另请参阅使用 Math.min 和 Math.max

更新要读取文件,请创建一个新方法 public void readFile () {...}

在这里

 boolean firstLine = true;
Scanner input = new Scanner(new FileInputStream(<file>));
while (input.hasNextLine()) {
String line = input.nextLine();
if (firstLine) {
setTeamName (line);
firstLine = false;
continue;
}

// convert line to Double
// perform Math
}

关于java - 使用类读取txt文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20367795/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com