Source of ForLoop.java


  1: import java.util.Scanner;

  3: /**
  4:  * Using a for loop to read a specific number of elements.
  5:  *
  6:  * @author Mark Young (A00000000)
  7:  */
  8: public class ForLoop {

 10:     /**
 11:      * Run this program.
 12:      *
 13:      * @param args command lines arguments (ignored)
 14:      */
 15:     public static void main(String[] args) {
 16:         // introduce yourself
 17:         System.out.println("\n"
 18:             + "Average Grade Calculator\n"
 19:             + "------------------------\n\n"
 20:             + "This program calculates your average assignment grade.\n");
 21:         System.out.println("You need to know all your grades.\n");

 23:         // create variables
 24:         Scanner kbd = new Scanner(System.in);
 25:         int numAsgn = 6;
 26:         double sum = 0.0;
 27:         double grade;
 28:         double ave;

 30:         // read and sum all grades
 31:         for (int a = 1; a <= 6; ++a) {
 32:             System.out.print("Enter your grade on A-" + a + ": ");
 33:             grade = kbd.nextDouble();
 34:             kbd.nextLine();
 35:             sum += grade;
 36:         }
 37:         System.out.println();

 39:         // calculate and print the average
 40:         ave = sum / numAsgn;
 41:         System.out.println("Your average grade was " + ave + ".");
 42:         System.out.println();
 43:     }

 45: }