Thursday, October 20, 2011

Java Equivalent of ITC110 Assignment 4

This is an assignment that deals with loops and arrays. It uses two array one for Grades and one for Credits. The purpose of the program is to calculate a GPA. The arrays are created in one method and then passed to another where they are filled in a for loop. Then they are passed to a third method where the arrays are multiplied together and summed to get the GPA.

Two other loops are added. One, a while loop in main, lets the user repeat the program as often as they wish. They enter 0 to exit. The other, a do loop, is used in the FillArrays method to make sure the grade is between 0 and 4. It will not allow the user to continue until they have entered a grade in the valid range. The grade is not written to the array until it is valid.

Here is the Java code


import java.util.Scanner;

public class GPACalculator {

 /**
  * This program calculates a GPA 
  * to do so it uses parallel arrays
  * one for grades and one for credits
  * it checks to make sure grades are
  * between 0 and 4
  * this program is the java equivalent
  * of ITC110 assignment 4
  * Steve Conger !0/20/2011
  */
 //declare the scanner globally
 Scanner reader = new Scanner(System.in);
 
 public static void main(String[] args) {
  GPACalculator calc=new GPACalculator();
  int choice=1;
  while(choice !=0)
  {
   calc.CreateArrays();
   System.out.println("Do you want to enter more grades: 0 to exit");
   choice=calc.reader.nextInt();
  }
  
 }
 
 private void CreateArrays()
 {
  
  System.out.println("How many grades do you want to enter?");
  int number=reader.nextInt();
  
  //declare the arrays
  double[] grades = new double[number];
  double[] credits=new double[number];
  
  //call the FillArrays method
  FillArrays(grades, credits);
 }
 
 private void FillArrays(double[] grades, double[]credits)
 {
  //loop through and fill the arrays)
  for(int i=0;i<grades.length; i ++)
  {
   //the do loop makes sure the grade is in 
   //the proper range
   double grade=0;
   do
   {
   System.out.println("Enter the grade");
   grade=reader.nextDouble();
   if(grade<0 || grade>4)
   {
    System.out.println("Grades must be between 0 and 4");
   }
   }while (grade<0 || grade>4);
   grades[i]=grade;
   System.out.println("Enter the credits");
   credits[i]=reader.nextDouble();
  }
  //call the CalculateGPA method
  CalculateGPA(grades, credits);
 }
 
 private void CalculateGPA(double[] grades, double[]credits)
 {
  double weight=0;
  double totalCredits=0;
  
  for(int i=0;i<grades.length; i ++)
  {
   weight += grades[i] * credits[i];
   totalCredits += credits[i];
  }
  
  double gpa = weight / totalCredits;
  System.out.println("Your GPA is " + gpa);
  
 }
 

}

No comments:

Post a Comment