-4

我需要使用双向量来存储学生的平均值。

我从中读取的文件是这样设置的:

2  //num of students
60   //total possible score
John   //name
4 16 9 7 10  //scores

所以我需要将字符串转换为双精度,将行中的所有整数相加,除以平均值,然后将平均值存储到双精度向量中。

我到目前为止的代码是:

public static String line;
public static Scanner in = new Scanner(System.in);
public static void main(String[] args) {


    System.out.println("enter the name of your file");
    String filename = in.next();
    FileIn file = new FileIn(filename);

    String firstLine; // String to hold first line which is number of students total in file.
    String secondLine; //String to hold second line which is number of points available 


    ArrayList<String> students = new ArrayList<String>();  // holds the students names

    //reads first line of the file. sets that number as the number of students
    firstLine = file.read();
    int numStu = Integer.parseInt(firstLine);
    // Just to test that number is being read correctly.
    System.out.println(numStu + " Number of students");

    //reads the second line of the file. sets that number as the total possible points in a semester
    secondLine = file.read();
    int totalPoints = Integer.parseInt(secondLine);
    // Just to test that number is being read correctly.
    System.out.println(totalPoints + " Total possible points");


    double avg = 0;
    double[]vector = new double [numStu]; 

    readFile(students,numStu,file,vector, avg);

    System.out.println(students);
    System.out.println(vector);
}

//puts the names into an arraylist and scores into a double vector
public static void readFile(ArrayList<String> students,int numStu, FileIn file, double[]vector, double avg)
{
    for(int k=0; k<(numStu*2); k++)
    {
                    //odd numbers are the students
        if (k % 2 == 0)
            students.add(file.read());

        else
        {
            //code to read and add the numbers from one line together, and storing the added and averaged score
        }
    }
}

}

如您所见,我缺少将文件元素分配到双向量的底部

我的 FileIn 类如下所示:

private String myFileName;
private BufferedReader myFile;
public FileIn(String filename)
{
    myFileName = filename;
    try
    {
        myFile = new BufferedReader(new FileReader(myFileName));
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }
    finally{}
}

public String read()
{
    String myLine = new String();
    try
    {
        myLine = myFile.readLine();
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }
    finally{}
    return myLine;
}

}

4

1 回答 1

0

第一!请在您的问题下阅读我的评论。学习如何以更聪明的方式提问,并学会分而治之。

这不是您问题的直接答案,因为我认为程序员应该能够自己解决它并学习它以用于您的问题。

完成以下一段代码,完成后您将知道自己问题的答案。

public class Foo {
  public static int main(String[] args) {
    String input = "10 15 20.5 70 40";

    // write code to convert the input string to doubles and sum them up
    double sum = ......;

    // answer should equals to 155.5
  }
}

提示:String.split()and Double.parseDouble(), and 使用 for 循环

于 2013-01-14T02:10:45.423 回答