# Thread: stuck on an assignment

1. Member Join Date
Jul 2008
Posts
8
Rep Power
0

## stuck on an assignment

I am in a Java class and I have an assignment that I am really stuck on.

Here is the assignment:

Write a program that reads a student's name together with his or her test scores. The program should then compute the average test score for each student and assign the appropriate grade. The grade scale is as follows: 90-100,A ; 80-89,B ; 70-79,C ; 60-69,D ; 0-59,F.

Your program must use the following methods;

a. A void method, calculateAverage, to determine the average of the five test scores for each student. Use a loop to read and sum the five test scores. (This method does not output the average test score. That task must be done in the method main.)

b. A value-returning method, calculateGrade, to determine and return each student's grade. (This method does not output the grade. That task must be done in the method main.)

Test your program on the following data. Read the data from a file and send the output to a file. Use the appropriate parameters to pass the values in and out of the methods.

Johnson 85 83 77 91 76
Aniston 80 90 95 93 48
Cooper 78 81 11 90 73
Gupta 92 83 30 69 87
Blair 23 45 96 38 59
Clark 60 85 45 39 67
Kennedy 77 31 52 74 83
Bronson 93 94 89 77 97
Sunny 79 85 28 93 82
Smith 85 72 49 75 63

I have been staring at this problem for hours trying to figure out just how to execute it but I am having a lot of trouble. I am trying to figure out just how to get the average grade for each student. Now I know how to add the five together and divide by 5 (the number of test scores). I understand the math I am having a hard time figuring out how to code it the way the book wants me to.

Any suggestions, tips, examples, help, ect. will be greatly appreciated! Thanks a ton!  Reply With Quote

2. ## Your progress

Hello starchildren3317

Please post your current code, or the section that you are having trouble with. Or is it that you are not certain how to start? :p  Reply With Quote

3. Member Join Date
Jul 2008
Posts
8
Rep Power
0

## well I am not really even certain how to start. I know how I am going to calculate the grade. The problem is that I am uncertain how I am going to get the average student grade for each student.

For example, in calculateAverage void method do I input five grades at a time and then average them? and then the next five? How would I go about doing that? How would I then send it back to main for the output? I am really stuck hehe.  Reply With Quote

4. ## DataInputStream

There is a file type DataInputStream, which may be used on the basis that the structure of the file is known beforehand. Read the docs on that and let us know if you could read in the file with DataInputStream.  Reply With Quote

5. ## Solve the problem one step at a time.
First step, write a program that will read the file line by line.
Next step, break the line up into its parts, name and scores.
Next step, convert the scores from strings to numbers.
etc.
Write the program to do step one and get it to work,
then move to step two, etc
Add some println() statements to the program to show values as you read data and process it.

As you have problems and need help, post the errors you are getting along with the code and ask another question about how to fix the error.

There are several coding examples posted on this site. Use search for examples. For example look for BufferedReader for how to read a file.

Regarding the assignment specs:
void method, calculateAverage
What do you do with the results of the calculation? Does this imply a class for each student that you pass the raw scores to and it does the calc and stores the average in a class variable?

Where do you store the value this method returns? Is this a method in a student class or in the main class?

Sorry, I'm not really sure what your assignment is. Maybe some else can figure it out.
Last edited by Norm; 07-19-2008 at 12:47 AM.  Reply With Quote

6. Member Join Date
Jul 2008
Posts
8
Rep Power
0

## This is what I have for calculateAverage:

Java Code:
```Public void calculateAverage(array Average[]) {
for (int i = 0; i < Average.length; i++) {
Average[i] = console.nextInt();

}

}```
Here is what is taken from the file:

Test your program on the following data. Read the data from a file and send the output to a file. Use the appropriate parameters to pass the values in and out of the methods.

Johnson 85 83 77 91 76
Aniston 80 90 95 93 48
Cooper 78 81 11 90 73
Gupta 92 83 30 69 87
Blair 23 45 96 38 59
Clark 60 85 45 39 67
Kennedy 77 31 52 74 83
Bronson 93 94 89 77 97
Sunny 79 85 28 93 82
Smith 85 72 49 75 63
Now wont this total all the grades and then / by 5?

What I need is an average for each student's grades gotten from the file.  Reply With Quote

7. ## You need to show all of the program.
Comment on coding style:
Public void calculateAverage(array Average[])
What are the args to calculateAverage? What is the type array?
Java coding standards/conventions Uppercase the name of the class and lowercase the variable name. Also the [] is usually put on the type vs the variable. Like so:
public void calculateAverage(Array[] average)

The code you show will add together all the data returned by console.nextIng(). If only the scores for one student are returned, then that students grade will be computed. What you need to do is have a place to store the averages for each student. You could use an array for that.
What is the purpose of putting the scores into the array average?

YOU need to DOCUMENT your code describing why you are doing each step.
Last edited by Norm; 07-19-2008 at 04:42 PM.  Reply With Quote

8. Member Join Date
Jul 2008
Posts
8
Rep Power
0

## OK I am a little closer but still stuck and the assignment is due in a couple of days. Here is what I have for code:

Java Code:
```import java.io.*;
import java.util.*;

public class CH07EX14 {

/** Author: Shane C. Sargent
* Assignment 5, Chapt. 07 Example 14
* Created: 07/  /08
*/
public static void main(String[] args)
throws FileNotFoundException {

Scanner inFile = new Scanner (new FileReader ("h:\\assignment5.txt"));
PrintWriter outFile = new PrintWriter("chapt07//CH07EX14.out");

String stuJ = inFile.next(); //Gather the Student names from the in file
String stuA = inFile.next(); //and assign them to String variables.
String stuCo = inFile.next();
String stuG = inFile.next();
String stuBl = inFile.next();
String stuCl = inFile.next();
String stuK = inFile.next();
String stuBr = inFile.next();
String stuSu = inFile.next();
String stuSm = inFile.next();

calculateAverage(); //Void Method

double classAverage = 10 / (aveJ + aveA + aveCo + aveG + aveBl + aveCL + aveK + aveBr + aveSu + aveSm); //calculate the entire class average.

System.out.println("Student    Test1   Test2   Test3   Test4   Test5   Average   Grade");

}
public static void calculateAverage() {

double aveJ, aveA, aveCo, aveG, aveBl, aveCl, aveK, aveBr, aveSu, aveSm;

int[] testScore = new int; //create an array named testScore with 50 components.

for (int i = 0; i < testScore.length; i++) {
testScore[i] = inFile.nextInt(); //Gathers the 50 test scores from the in file and stores them into the array.

aveJ = 5 / (testScore + testScore + testScore + testScore + testScore); //Collects each student's 5 test scores
aveA = 5 / (testScore + testScore + testScore + testScore + testScore); //adds them together and divide by 5
aveCo = 5 / (testScore + testScore + testScore + testScore + testScore); //to get the average grade for each student.
aveG = 5 / (testScore + testScore + testScore + testScore + testScore);
aveBl = 5 / (testScore + testScore + testScore + testScore + testScore);
aveCl = 5 / (testScore + testScore + testScore + testScore + testScore);
aveK = 5 / (testScore + testScore + testScore + testScore + testScore);
aveBr = 5 / (testScore + testScore + testScore + testScore + testScore);
aveSu = 5 / (testScore + testScore + testScore + testScore + testScore);
aveSm = 5 / (testScore + testScore + testScore + testScore + testScore);
}

if (average >= 90) //Collect each students average grade
return "A";    //and return the letter grade.
else if (average >= 80)
return "B";
else if (average >= 70)
return "C";
else if (average >= 60)
return "D";
else
return "F";
}
}
}```
Here are a few areas where I am stuck:

In calculateAverage: inFile.nextInt(); comes up with an error. It needs to access the scanner infile so that it can collect the test grades but I am unsure of how to do that.

In calculateGrade: this method needs to access the student's averages calculated in calculateAverage so that it can get the letter grade. It then will need to pass it to main somehow.

In main at double classAverage: it needs to access calculateAverage in order to get the student averages so it can get a class average. (main in general needs to have access to what is calculated in the two methods so that I can do some calculating and printing in main, I am just not sure how to do it.  Reply With Quote

9. ## Here are a few observations:
Your definition doesn't return anything (void).
There needs to be a variable to return the data to:

To compute an average: add all the numbers together and divide by the number of numbers. Your code does it backwards.
double aveJ, aveA, aveCo, aveG, aveBl, aveCl, aveK, aveBr, aveSu, aveSm;
These variables need to be outside the method for other methods to be able to see them.

Put some System.out.println() statements in the program to see the values of the variables after they are read in to be sure that they are what you expect. I think stuA might be 85, the second token on the first record.

The program MUST be redesigned.
You can NOT use the number of lines (and contents) of the data your are reading to build your program. Your program will only work with the input that you have been given. What if the number of lines is changed from 1o to 25? Or the names/order of the students is changed.

You need to use some kind of container like an array, a Vector or an ArrayList to hold the data as it is read in and separated into names and grades.  Reply With Quote

10. ## Java Code:
```import java.io.*;
import java.util.*;

public class Ex14 {
public static void main(String[] args) throws IOException {
// Read data file and collect information.
List<String> data = new ArrayList<String>();
String inPath = "ex14.txt";
Scanner scanner = new Scanner(new File(inPath));
while(scanner.hasNextLine()) {
}
scanner.close();

// Check data.
//for(String s : data)
//    System.out.println(s);

// Use data to initialize arrays used in this class.
int size = data.size();
String[] names = new String[size];

// How many grades are there for each student?

// Fill [i]names[/i] and [i]gradeStrings[/i] arrays.
for(int i = 0; i < size; i++) {
String line = data.get(i);
int firstSpace = line.indexOf(" ");
// Pick off the first word.
names[i] = line.substring(0, firstSpace);
// Save the rest of the line for later.
}

for(int i = 0; i < size; i++) {
for(int j = 0; j < strs.length; j++) {
}
}

// All data should be prepared for calculations.
// Just to see what we've done:
for(int i = 0; i < size; i++) {
System.out.printf("%7s  %s%n", names[i],
}

// Collect grade totals of each students.
// This method will fill the array.

// Collect the letter grades for each student.
for(int i = 0; i < names.length; i++) {
}

// Write results to file.
String outPath = "ex14Results.txt";
BufferedWriter bw = new BufferedWriter(
new OutputStreamWriter(
new FileOutputStream(outPath)));
for(int i = 0; i < size; i++) {
String line = names[i] + " " + letterGrades[i];
bw.write(line, 0, line.length());
bw.newLine();
}
bw.close();
}

// Add up the grades for each student and save as a
// corresponding element in the [i]array[/i] array.
// This method does not return anything but it does
// fill the local variable [i]array[/i] with data.
private static void calculateAverage(int[] array, int[][] grades) {
for(int i = 0; i < grades.length; i++) {
for(int j = 0; j < grades[i].length; j++) {
}
}
}

// Return type in method delcaration must match the
// type returned from the method, here, type String.
private static String calculateGrade(double average) {
return "A";    //and return the letter grade.
else if (average >= 80)
return "B";
else if (average >= 70)
return "C";
else if (average >= 60)
return "D";
else
return "F";
}
}```  Reply With Quote

11. ## startchildren3317 be sure to give credit to hardwired when you turn in his code.  Reply With Quote

12. Member Join Date
Nov 2008
Posts
1
Rep Power
0

## I believe since this is from chapter 7 (problem 14) you cannot use an array to solve this problem. Arrays are learned in chapter 10 or so. You can use:

Java Code:
```import java.util.*;
import java.io.*;

public class Chp7_14
{
public static void main(String[] args) throws FileNotFoundException
{

Scanner inFile = new Scanner(new FileReader ("students.txt"));
PrintWriter outFile = new PrintWriter("output.txt");
double classSum = 0;
int studentCount = 0;
double classAverage = 0;
DoubleClass studentAvg = new DoubleClass();

outFile.println("Student    Test1 Test2 Test3 Test4 Test5 Average Grade");

while(inFile.hasNext())
{
studentCount++;
calculateAverage(inFile, outFile, studentAvg);
classSum += studentAvg.getNum();
}

if (studentCount > 0)
classAverage = classSum / studentCount;

outFile.println("\n\nClass Average = " + classAverage);

inFile.close();
outFile.close();

}// end main

public static void calculateAverage(Scanner iFile, PrintWriter oFile, DoubleClass studentAverage)
{
String name;
int test;
double average;
int sum;
sum = 0;
name = iFile.next();
oFile.printf("%-9s  ", name);

for (int count = 0; count < 5; count++)
{
test = iFile.nextInt();
oFile.printf("%4d  ", test);
sum = sum + test;

}

average = sum/5.0;
studentAverage.setNum(average);
oFile.printf("%n");

}// end void

{
return "A";        //and return the letter grade.
else if (average >= 80)
return "B";
else if (average >= 70)
return "C";
else if (average >= 60)
return "D";
else
return "F";
}

}```
but youll need the class DoubleClass in the same directory as your assignment.

Java Code:
```/**
DoubleClass allows for the instantiation of an object that contains one instance variable of type double.
Appropriate methods have been defined to manipulate instance variable.  Class created by John Zamora 11/12/2008.
*/
public class DoubleClass
{
/** Object of this class represents a double primitive data type.
Instance variable is a double value.
*/
double doubleNum;

/**
Default constructor: Sets instance variable to 0.0.
*/
public DoubleClass()
{
doubleNum = 0.0;
}
/**
Constructor: Sets instance variable to double value passed as parameter.
*/
public DoubleClass(double num)
{
doubleNum = num;
}
/**
Accessor Method:  Returns value of instance variable.
*/
public double getNum()
{
return doubleNum;
}
/**
Mutator Method:  Set instance variable to value passed as parameter.
*/
// mutator method
public void setNum(double num)
{
doubleNum = num;
}

} // end class DoubleClass```
this post is probably way past due for the person actually wanting this, but for the future because I'm sure many other people trying to learn java like myself.  Reply With Quote

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•