使用Classes读取文本文件

时间:2013-12-04 05:40:25

标签: java arrays class text java-7

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

更新: 我相信我已经阅读了txt文件中的团队名称,现在我读到的击球平均数是多少

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.
 }
    }

2 个答案:

答案 0 :(得分:1)

这是一个提示。

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

另请参阅使用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
}

答案 1 :(得分:0)

使用

Scanner input = new Scanner(new FileInputStream(<file>));
while (input.hasNextLine()) {
   String line = input.nextLine();
   ....
}

从文件中读取文本行。