Results 1 to 12 of 12
  1. #1
    Join Date
    Jul 2008
    Posts
    8
    Rep Power
    0

    Default 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!

  2. #2
    tim's Avatar
    tim
    tim is offline Senior Member
    Join Date
    Dec 2007
    Posts
    435
    Rep Power
    7

    Default 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
    Eyes dwelling into the past are blind to what lies in the future. Step carefully.

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

    Default

    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.

  4. #4
    Nicholas Jordan's Avatar
    Nicholas Jordan is offline Senior Member
    Join Date
    Jun 2008
    Location
    Southwest
    Posts
    1,018
    Rep Power
    8

    Default 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.
    Introduction to Programming Using Java.
    Cybercartography: A new theoretical construct proposed by D.R. Fraser Taylor

  5. #5
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,390
    Rep Power
    25

    Default

    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?

    value-returning method, calculateGrade
    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.

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

    Default

    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();
    
    Grade += Average[i] ;
    }
    
    AverageGrade = Grade / 5;
    }
    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.

  7. #7
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,390
    Rep Power
    25

    Default

    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.

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

    Default

    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
    		calculateGrade();  //Value-Returning 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[50]; //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[0] + testScore[1] + testScore[2] + testScore[3] + testScore[4]); //Collects each student's 5 test scores
        		aveA = 5 / (testScore[5] + testScore[6] + testScore[7] + testScore[8] + testScore[9]); //adds them together and divide by 5
        		aveCo = 5 / (testScore[10] + testScore[11] + testScore[12] + testScore[13] + testScore[14]); //to get the average grade for each student.
        		aveG = 5 / (testScore[15] + testScore[16] + testScore[17] + testScore[18] + testScore[19]);
        		aveBl = 5 / (testScore[20] + testScore[21] + testScore[22] + testScore[23] + testScore[24]);
        		aveCl = 5 / (testScore[25] + testScore[26] + testScore[27] + testScore[28] + testScore[29]);
        		aveK = 5 / (testScore[30] + testScore[31] + testScore[32] + testScore[33] + testScore[34]);
        		aveBr = 5 / (testScore[35] + testScore[36] + testScore[37] + testScore[38] + testScore[39]);
        		aveSu = 5 / (testScore[40] + testScore[41] + testScore[42] + testScore[43] + testScore[44]);
        		aveSm = 5 / (testScore[45] + testScore[46] + testScore[47] + testScore[48] + testScore[49]);
        	}
        public static void calculateGrade() {
        	
        	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.

  9. #9
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,390
    Rep Power
    25

    Default

    Here are a few observations:
    value-returning method, calculateGrade
    public static void calculateGrade() {
    Your definition doesn't return anything (void).
    calculateGrade(); //Value-Returning Method
    There needs to be a variable to return the data to:
    <variable> = calculateGrade(); // get grade

    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.

  10. #10
    hardwired's Avatar
    hardwired is offline Senior Member
    Join Date
    Jul 2007
    Posts
    1,576
    Rep Power
    9

    Default

    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()) {
                data.add(scanner.nextLine());
            }
            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];
            String[] gradeStrs = new String[size];
    
            // How many grades are there for each student?
            int numGrades = data.get(0).split("\\s").length -1;
            //System.out.println("numGrades = " + numGrades);
            int[][] grades = new int[size][numGrades];
    
            // 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.
                gradeStrs[i] = line.substring(firstSpace+1);
            }
    
            // Parse [i]gradeStrs[/i] and fill [i]grades[/i] arrays.
            for(int i = 0; i < size; i++) {
                String[] strs = gradeStrs[i].split("\\s");
                for(int j = 0; j < strs.length; j++) {
                    grades[i][j] = Integer.parseInt(strs[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],
                                   Arrays.toString(grades[i]));
            }
    
            // Call your methods.
            // Collect grade totals of each students.
            int[] gradeTotals = new int[size];
            // This method will fill the array.
            calculateAverage(gradeTotals, grades);
    
            // Collect the letter grades for each student.
            String[] letterGrades = new String[size];
            // Fill [i]letterGrades[/i] array.
            for(int i = 0; i < names.length; i++) {
                double average = gradeTotals[i]/numGrades;
                letterGrades[i] = calculateGrade(average);
            }
    
            // 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++) {
                    array[i] += grades[i][j];
                }
            }
        }
    
        // Return type in method delcaration must match the
        // type returned from the method, here, type String.
        private static String calculateGrade(double average) {
        	if (average >= 90)     //Receive 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";
        }
    }

  11. #11
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,390
    Rep Power
    25

    Default

    startchildren3317 be sure to give credit to hardwired when you turn in his code.

  12. #12
    nigjistic is offline Member
    Join Date
    Nov 2008
    Posts
    1
    Rep Power
    0

    Default

    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;
    		String grade;
    		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);
    		grade = calculateGrade(average);
    		oFile.printf("%5.1f  %3s", average, grade);
    		oFile.printf("%n");
    
    
    
    
    
    
    	}// end void
    
    
    
    
    	private static String calculateGrade(double average)
    	       {
    	       	if (average >= 90)     //Receive 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";
              }
    
    
    }
    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.

Similar Threads

  1. musically stuck cry for help 2
    By geork in forum New To Java
    Replies: 0
    Last Post: 02-07-2008, 02:09 PM
  2. musically stuck
    By geork in forum New To Java
    Replies: 1
    Last Post: 02-06-2008, 09:44 PM
  3. Stuck and Frustrated.
    By jazzinspace in forum New To Java
    Replies: 7
    Last Post: 01-12-2008, 02:38 PM
  4. Replies: 3
    Last Post: 12-05-2007, 02:22 AM
  5. I am completely stuck
    By jpnym15 in forum New To Java
    Replies: 2
    Last Post: 11-14-2007, 06:40 PM

Posting Permissions

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