Computer Science Canada Arrays in a marks program |
Author: | .:hacker:. [ Wed Apr 20, 2005 5:55 pm ] |
Post subject: | Arrays in a marks program |
I've been working on a small marks program with arrays recently. It supposed to let the user enter ten marks, and then give the average, minimum mark, and maximum mark. The problem is, I don't know how. This kind of stuff always stumps me, for some reason. Can anybody help with some suggestions? (incomplete code is below) public class ArrayPractice { int [] marks = new int[10]; int i; int intMarks; String Marks; int intAverage; int intMinimum; int intMaximum; public static void main (String [] args) { for (int i=0; i<10;i++) { System.out.println ("Please enter your ten marks: "); Marks = kb.readLine (); intMarks=Integer.parseInt(Marks); public int findMin(int[]intArray) { int minIndex = 0; for (int i = 1; i < intArray.length;i++) { if(intArray[i]<intArray[minIndex]) { minIndex = i; } } } System.out.println ("Your average mark is: " + intAverage); System.out.println ("The minimum mark is: " + intMinimum); System.out.println ("The maximum mark is: " + intMaximum); } } } |
Author: | wtd [ Wed Apr 20, 2005 7:55 pm ] | ||||||||||||||
Post subject: | |||||||||||||||
Thinking in an object-oeitned nature... Let's look at the problem You need to get 10 grades from the user via a keyboard, then find the minimum, maximum, and average grade. So, what do we need? We need an object which can store ten grades. Such an object should at minimum have a way to add a grade. Let's construct the basics:
Of course, we need something to store grades in, and a way to keep track of how many we have at any given moment. Of course we'll also need a constructor to setup these things.
Now, there's a problem here. If we try to add 11 grades, we'll get an exception. So, we need to catch any ArrayOutOfBoundsException that might occur and basically do nothing.
Now, to get the average grade we have to get the sum.
Averaging the grades falls out pretty naturally from that as simple division.
Now, we need to find the minimum and maximum. Well, start with the first grade, and compare it to the second grade. For minimum, if the second grade is smaller, that's your new minimum grade. If it's greater than or equal to the first grade, then you keep the first grade as your minimum. Continue throughout the grades. Do the same but in reverse for finding the maximum grade.
Fill in the rest, since I'm not going to do all of your homework for you. Hint though: see the sumGrades() method to see how to loop over the grades. Now, to use that in your program.
|