Problem Solving and Computing (CSC-103 98S)

[Instructions] [Search] [Current] [Changes] [Syllabus] [Handouts] [Outlines] [Journal] [Problems] [Computing] [SamR Docs] [Tutorial] [API]


Computing Assignment 5: Control Structures

Assigned: Thursday, February 12, 1998
Due: Tuesday, February 24, 1998

Purpose: In this assignment, you will attempt to develop more complex programs. Along the way, you will gain an understanding of the control structures that Java uses to help control the exeuction of a program. These control structures include subroutines (methods), conditionals (if), and loops (while and for).

Warning: At times, Java is incredibly verbose. At other times, it is confusingly terse. Why do we do things the way we do? Because the designers decided that we whould. (I.e., "it's just the way things are").

Background

Recall that there are three basic steps to building a Java program:

Of course, when creating a program from scratch, you should begin by sketching the design of the program: what it does and how it does it.

Subroutines

Recall that to define a subroutine you must write the type, name, parameters, and body of that subroutine. To use a subroutine, you must build a corresponding object and write the name of the object followed by the name of the subroutine follwed by the parameters to the subroutine.

Squares, Revisited

Here is a revised version of our Square program that uses a subroutine to compute the square of a number. By using two nested calls to that subroutine, it can also compute a 4th power of the number.



import rebelsky.io.SimpleInput;
import rebelsky.io.SimpleOutput;

/**
 * A simple Java program that illustrates numeric input and output
 * and the use of subroutines.
 *
 * @author Samuel A. Rebelsky
 * @version 1.1 of February 1998
 */
public class NewSquare
{
   /**
    * Compute the square of a number.
    */
   public double square(double param)
   {
     return param*param;
   } // square

   /**
    * Prompt for a number and print the square of the number.
    */
   public static void main(String[] args) 
   {
      // The object we're using to read input.
      SimpleInput in = new SimpleInput();
      // The object we're using to print output.
      SimpleOutput out = new SimpleOutput();
      // The object that does the computation.
      NewSquare compute = new NewSquare();
      // The value entered.
      double val;
      // Prompt for the value.
      out.print("Please enter a value and I will square it: ");
      // Get the name.
      val = in.readDouble();
      // Print a friendly message.
      out.println(val + " squared is " + compute.square(val));
      // Print another friendly message.
      out.println(val + " to the fourth is " + 
                  compute.square(compute.square(val)));
      // That's it
      System.exit(0);
   } // main
} // NewSquare



You may want to save, compile, and run this program to verify that it works.

Temperatures, Revisited

Building on your conversion routine from the previous exercise, write a method that converts Fahrenheit to Centigrade and a method that converts Centigrade to Fahrenheit. Use them together to enter a number and convert it in both ways.


Conditionals

As you may know, we use conditionals to do different things based on different conditions.

Absolute values

One simple use of conditionals is in computing absolute values.



import rebelsky.io.SimpleInput;
import rebelsky.io.SimpleOutput;

/**
 * A simple Java program that illustrates the use of subroutines
 * and conditionals.
 *
 * @author Samuel A. Rebelsky
 * @version 1.0 of February 1998
 */
public class AbsoluteValue
{
   /**
    * Compute the absolute value of a number
    */
   public double abs(double param)
   {
      // If the number is less than 0, multiply by -1
      if (param < 0) {
         return -1 * param;
      } // if negative
      // Otherwise, just return the number
      else {
         return param;
      } // if positive
   } // abs

   /**
    * Prompt for a number and print the square of the number.
    */
   public static void main(String[] args) 
   {
      // The object we're using to read input.
      SimpleInput in = new SimpleInput();
      // The object we're using to print output.
      SimpleOutput out = new SimpleOutput();
      // The object that does the computation.
      AbsoluteValue compute = new AbsoluteValue();
      // The value entered.
      double val;
      // Prompt for the value.
      out.print("Please enter a value: ");
      // Get the name.
      val = in.readDouble();
      // Print a friendly message.
      out.println("The absolute value of " + val + " is " + compute.abs(val));
      // That's it
      System.exit(0);
   } // main
} // AbsoluteValue



You may want to save, compile, and execute this program to make sure that it works.

Letter Grades

Often, we nest conditionals to try things in order, using a cascading series of if-then-else's. Let's create a simple program that reads a numeric grade and prints out a corresponding letter grade.



import rebelsky.io.SimpleInput;
import rebelsky.io.SimpleOutput;

/**
 * A simple Java program that requests letter grades and prints out
 * numeric grades.
 *
 * @author Samuel A. Rebelsky
 * @version 1.0 of February 1998
 */
public class LetterGrade
{
   /** 
    * Convert a numeric grade to a letter grade.
    */
   public String letter(double grade) {
      if (grade >= 94) {
         return "A";
      }
      else if (grade >= 90) {
         return "A-";
      }
      else if (grade >= 87) {
         return "B+";
      }
      else if (grade >= 84) {
         return "B";
      }
      else if (grade >= 80) {
         return "B-";
      }
      else {
         return "F";
      }
   } // letter
  
   /**
    * Prompt for a number and print the square of the number.
    */
   public static void main(String[] args) 
   {
      // The object we're using to read input.
      SimpleInput in = new SimpleInput();
      // The object we're using to print output.
      SimpleOutput out = new SimpleOutput();
      // The object that does the computation.
      LetterGrade grader = new LetterGrade();
      // The value entered.
      double val;
      // Prompt for the value.
      out.print("Please enter a numeric grade: ");
      // Get the value.
      val = in.readDouble();
      // Print a friendly message.
      out.println("That is a(n) " + grader.letter(val));
      // That's it
      System.exit(0);
   } // main
} // LetterGrade



Grade Averaging

Write a program that reads in three letter grades and computes their numeric average using Grinnell's normal point scale (an A is worth 4 points, an A- is worth 3.66 points, a B+ is worth 3.33 points, a B is worth 3 points, and so on and so forth). You'll need to use in.readLine() to read the letter grades. You can compare two strings using the equals method, as in

if (grade.equals("A")) {
   ...
}


while Loops and Repetition

As you may have noted from some of the previous problems, we often want to do things repeatedly. For example, we might want to convert a sequence of numbers from Fahrenheit to Centrigade, average an arbitrary number of numbers, and so on and so forth.

Computing many letter grades

It can be frustrating to run the LetterGrade program again and again and again. Therefore, it might be more useful to keep prompting for the next grade to enter, stopping when the user enters a special number (e.g., something less than zero). Here's a program that does just that.



import rebelsky.io.SimpleInput;
import rebelsky.io.SimpleOutput;

/**
 * A simple Java program that requests letter grades and prints out
 * numeric grades.
 *
 * @author Samuel A. Rebelsky
 * @version 1.0 of February 1998
 */
public class ManyGrades
{
   /** 
    * Convert a numeric grade to a letter grade.
    */
   public String letter(double grade) {
      if (grade >= 94) {
         return "A";
      }
      else if (grade >= 90) {
         return "A-";
      }
      else if (grade >= 87) {
         return "B+";
      }
      else if (grade >= 84) {
         return "B";
      }
      else if (grade >= 80) {
         return "B-";
      }
      else {
         return "F";
      }
   } // letter
  
   /**
    * Prompt for a number and print the square of the number.
    */
   public static void main(String[] args) 
   {
      // The object we're using to read input.
      SimpleInput in = new SimpleInput();
      // The object we're using to print output.
      SimpleOutput out = new SimpleOutput();
      // The object that does the computation.
      ManyGrades grader = new ManyGrades();
      // The value entered.
      double val = 0;
      // Keep prompting for values until the user enters a negative
      // value.
      while (val >= 0) {
         // Prompt for the value.
         out.print("Please enter a numeric grade (enter a negative number to stop): ");
         // Get the value.
         val = in.readDouble();
         // Print a friendly message.
         if (val >= 0) {
           out.println("That is a(n) " + grader.letter(val));
         }
      } // while
      // That's it
      System.exit(0);
   } // main
} // ManyGrades



Grade averaging, revisited

Extend your grade averaging program to average an arbitrary number of grades. Use some special letter (e.g., "Q") to indicate that the grades are completed. If the letter grade you are reading is called grade, you might use

while (!grade.equals("Q")) {
   ...
}
The ! is "Java-ese" for "not". Hence, the !grade.equals("Q") would be read 'grade does not equal "Q"'.

Before you start coding, sit down and work out the parts of this problem. Note that you'll need to figure out a way to compute an average without knowing in advance how many things you'll be averaging.

Grade averaging, re-revisited

Extend your previous program to input a number of credits along with each letter grade. Use readLineDouble() to read the number of credits. This is a slight variation of readDouble() that is more appropriate for the problem at hand. For example, a typical interaction with your program might resemble:

Enter a letter grade: B
How many credits is that B worth? 2
Your cumulative GPA is 3.0.
Enter a letter grade: A
How many credits is that A worth? 4
Your cumulative GPA is 3.6666666.
Enter a letter grade: Q
Bye!

Turning it In

Email me your version of the final program, using a command like
% elm rebelsky < GradeAverage.java (where you fill in the name of your own program).


[Instructions] [Search] [Current] [Changes] [Syllabus] [Handouts] [Outlines] [Journal] [Problems] [Computing] [SamR Docs] [Tutorial] [API]

Disclaimer Often, these pages were created "on the fly" with little, if any, proofreading. Any or all of the information on the pages may be incorrect. Please contact me if you notice errors.

Source text last modified Thu Feb 19 12:10:04 1998.

This page generated on Thu Apr 2 13:49:59 1998 by SiteWeaver.

Contact our webmaster at rebelsky@math.grin.edu