开发者

Why doesn't my exam mark averaging code work?

开发者 https://www.devze.com 2022-12-13 08:06 出处:网络
I\'m trying to get the program t开发者_如何学Co let me enter a users name and then a mark and display the average. This is what I\'ve tried:

I'm trying to get the program t开发者_如何学Co let me enter a users name and then a mark and display the average. This is what I've tried:

// Calculate Students Average of series of exam marks stored in an array
import uulib.GUI;

public class ExamMarks {

  public static void main(String[] args) {

    final int SIZE = 10;

    int[] marks = new int[SIZE];

    double total, average;

    String[] names = new String[]{""};


    // Read marks into array
    {
      String name;
      name = GUI.getString("Enter your name");
      GUI.show("Names"); 
    }

    for(int i=0; i<marks.length; i++) {
        marks[i] = GUI.getInt("Enter mark " + (i+1));
    }

    total = 0;
    // calculate average mark
    for(int i=0; i<marks.length; i++) {
        total = total + marks[i];
    }

    average = total/SIZE; 
    GUI.show("Average mark is " + average);
 }

}

I want it to ask for a name and then a mark ten times, and finally show the average. But it is only asking me for one name, after which it asks me for ten marks and gives me an average of these.


Some hints and observations:

  1. I guess you want to enter 1 Student and 10 marks and calculate the average for that student. So you may not need the names array (you only get one name)
  2. name is only visible inside the block. If you need the name outside of that block, just remove the curly braces.
  3. for your average calculation you may try casting the integer values to double, like (double) total / (double) SIZE) (even though casting just one value should be enough)

For GUI usage problems - you import a custom library, bet you have to double check the manual on how to use it.

EDIT

Your comment changed it a bit ;) Usually you would now create a small class like Result that holds a studentName attribute and a mark attribute (for simplification: we assume all students have unique names, so we don't need a studentID here).

If you feel better solving the task without a class, we can emulate it with to arrays, one for names and one for marks.

The following code demonstrates the flow:

public void process() {
  final int SIZE = 10;
  String[] names = new String[SIZE];
  int[] marks = new int[SIZE];
  for(int i = 0; i < SIZE; i++) {
    names[i] = readStudentNameFromGUI();
    marks[i] = readStudentsMarkFromGUI();
  }
  double average = calculateAverage(marks);
}

Note: there are some things you could (should) do better in Java, but I think that's easy enough to get an understanding and get a solution.

0

精彩评论

暂无评论...
验证码 换一张
取 消