Computer Science I

Welcome!

Steve Bruell
101D MLH
22C:16/106 Home Page

 

Introduction


Problem Solving with a Computer

  1. Describe the problem (the specification).
     
  2. Analyze the problem and design the data and algorithms needed for its solution.

    > English
    > Pseudo-code (combination of Java and English)
     
  3. Translate data definitions and algorithms into a Java program.
     
  4. Create a text file containing the Java program.
     
  5. Compile the program (translate it into a language the computer understands).

    > The compiler is a program that does the translation.
    > It may find syntax errors in the program and report them.
     
  6. Run the program.

    > Test and debug.

What is an Algorithm?

List of instructions for performing a process step-by-step.

Example: Automatic Gasoline Pump

  1. Press start button.
  2. Swipe credit card through reader.
  3. Press button choosing grade of gasoline.
  4. Insert nozzle into gas receptacle.
  5. Squeeze handle until pump shuts off.
  6. Replace nozzle in cradle.
  7. Press done button.
  8. Remove receipt.

    Two outcomes:

        Explicit result:    receipt
        Side effect:        tank is filled and credit card is debited


The Java Programming Language


The "Standard" First Java Program

Java Code:

public class Hello

{

   public static void main(String[] args)

   {

      // Print our message

      System.out.println("Hello, world!");

   }

}

What does each of these statements mean?

  1. The first line tells the compiler that we are starting a program called "Hello".  In order for the Java compiler to compile this program it must be saved in a file called "Hello.java".  We choose the names of our programs.  By convention we capitalize the first word of the program name, and every other word that might be in the name of our program.  For example, we could have named this program "HelloWorld".  We would then have to save it in a file called "HelloWorld.java".  It is illegal to have spaces in the names of our programs. The words "public" and "class" must appear in the exact order as shown here, and must be capitalized exactly the same as seen here. Their meaning will be explained later in the course. 
     
  2. The opening curly brace on the second line tells the compiler that we are starting the statements that are part of the "Hello" program. This curly brace is required by the compiler to be the first character, other than white space, after the name of our program.  By convention we place the curly brace directly under the "p" of public.  Whenever we use an open curly brace in Java, we always have a corresponding closing curly brace.  By convention, we place the closing curly brace directly under the open curly brace.  This makes our program easier to read.  The compiler doesn't care where on the line we place the closing curly brace, as long as we place one.  In our program, the last line contains the closing curly brace that matches our opening curly brace.  The compiler now knows that every statement between the second and last lines is part of our program.
     
  3. This Java program is executable by the Java runtime system because we have provided a "main" method.  The third line is where we provided the "main" method.  The meaning of the other words in the statement on the third line will be explained later in the course.  For now, provide them in the exact order shown with the exact punctuation shown.  
     
  4. The fourth line is the opening curly brace that tells the complier that we are starting the group of statements that make up our "main" method.  We placed this curly brace directly under the "p" to follow the Java convention.  The sixth line is the corresponding closing curly brace that closes our group of statements to be included in the "main" method.

    The lines that have been described to this point will be part of every program we write.  The name of the program will be the only thing that changes.
     
  5. The fifth line is a comment line.  Every computer programming language allows the programmer to insert comments into their code.  These comments are meant for the human reader of a program and not for the compiler.  The compiler will ignore all comments.  This example is of a one-line (or in-line) comment.  Java also has  "comment blocks" that are delimited by /* and */.
     
  6. The sixth line is a command in Java that tells the compiler to display some characters on the screen.  The letters between the quotation marks will be placed on the screen.  Wherever the cursor is when we start our program is where these characters will be placed.  This command will move the cursor to the start of the next line of the screen after it has displayed the characters between the quotes. This command is one of the commands we will use most in this course. 

    The System.out.println() command must always be told what to print on the screen.  We tell it what to print on the screen by "passing a parameter" to it.  In this program we are passing the parameter "Hello, world!".  We place the parameter to be passed to the command inside the parentheses. 

    The System.out.print() command does the same thing as the System.out.println() command, except that the cursor is not moved to the start of the next line.

    All commands in Java are terminated with a semicolon.  The compiler will generate an error message if we ask it to compile a command without the semicolon.  

Notice that the statements that are contained inside the curly braces are indented. This is not required by the compiler, but is done by convention to make the program easier to read for humans.  When looking at this sample program it is easy to see that each opening curly brace has its corresponding closing curly brace.  If we took out all of the carriage return / line feed characters in this program the compiler would not object.  But the program would not be very readable by humans.  As and example, can you tell if each opening curly brace has a corresponding closing curly brace in the following  program?

public class Hello{public static void main(String[] args){System.out.println("Hello, world!");}}


Tracing the Execution of a Program in Java


Two Basic Approaches to Programming

  1. Procedural Programming (PP)
     
  2. Object-Oriented Programming (OOP)
     

Solving a problem (Using Object-oriented Design)

Algorithm design is needed to describe the operations performed by the objects.
 

Example: Crazy-eight's Card Game

Objects Properties Behavior
     
Card Number
Suit
Display itself
Match another card
Card Deck Collection of cards Shuffle itself
Deal a card
Tell whether empty
Hand Collection of cards
Number of cards
Add a card
Remove a card
Discard Pile Collection of cards Add a card
Player Position
Hand
Play a turn


We begin the course with Procedural Programming to introduce the basic concepts of programming with Java. We will also introduce most of the commands available to a Java programmer.
 


Procedural Programming

Problem: Convert 86º fahrenheit into celsius

Algorithm:

    86º - 32º = 54º

     54º · 5 / 9 = 270º / 9 = 30º celsius

Write this calculation in Java output commands:

   System.out.print("86 degrees fahrenheit is equivalent to ");

   System.out.println((86 - 32) * 5 / 9 + " degrees celsius.");

Note:   "print" means print to screen without a return.
            "println" means print followed by a return.
            "+" means String concatenation.

Java code:

public class Degrees

{

   public static void main(String[] args)

   {

      System.out.println("87 degrees fahrenheit is equivalent to ");

      System.out.println((87 - 32) * 5 / 9 + " degrees celsius.");

   }

}

Problems:

  1. Computation done using integer arithmetic (in particular, division done using integer arithmetic)

    (87 - 32) * 5 / 9 = 30 instead of 30.56
    (87 - 32) * (5 / 9) = 0!

    Integer arithmetic
          35 / 4 = 8

    Real or floating-point arithmetic
          35.0 / 4.0 = 8.75

    Rule: If one or more operands are floating point, arithmetic is done in floating point, keeping the decimal part.
     
  2. Numbers hard-coded in output statements, so code may be hard to modify.

Variables

          Example of variable declaration:   

   int fahrDegrees;

   double celDegrees;

Assignment of Values to Variables

   fahrDegrees = 86;

   celDegress = (fahrDegrees - 32.0) * 5.0 /9.0;

Java Code:

public class Degrees1

{

   public static void main(String[] args)

   {

      int fahrDegrees;

      double celDegrees;



      fahrDegrees = 90;

      celDegrees = (fahrDegrees - 32.0) * 5.0 / 9.0;



      System.out.print(fahrDegrees + " degrees fahrenheit is equivalent to ");

      System.out.println(celDegrees + " degrees celsius.");

   }

}

Number Types

Numbers are stored with binary (base 2) representations inside the computer.

Two Basic Kinds

  1. Integer variables declared as type int are used to store integers.

    Range of values:

    -2,147,483,648 ≤ n ≤ 2,147,483,647
     
  2. Floating-point variables declared as type double are used to store real numbers.

    Similar to scientific notation: 5.17,  5.17E1 = 51.7,  5.17E2 = 517.0, 5.17E-1 = 0.517

    Range of values:

    -4.94065645841246544E-324 ≤ n ≤ 1.79769313486231570E+308

More on Variables

Declaration:    int num, count;

   num  

?

           
  count  

?

    

Declaration with initialization: int sum = 0, product = 1;

   sum 

0

 
 product   

1

 

Rule: Variables start with a letter and may continue with letters, digits, or underscores.

    Example:   

        double tax_factor1, tax_factor2;

    Example (better):

        double taxFactor1, taxFactor2;

Java convention: Begin variables with lowercase letters.


Arithmetic

Binary operations: +,     -,     *,     /,     %

        m % n is the remainder on dividing m by n

Precedence

        Higher: *,    /,    %
       
        Lower: +,    -

Left-to-right associativity (grouping)

        5 - 3 + 6 means (5 - 3) + 6, which evaluates to 8, not -4 (which would be obtained from 5 - (3 + 6)).

Parentheses are allowed to override precedence.

        5 - (3 + 6) evaluates to -4.

Examples:

        36 / 4 - 4 + 11 evaluates to 16

        8 + 13 / 5 * 2 evaluates to 12

        46 % 8 evaluates to 6

        76 % 10 % 3 evaluates to 0

        int m = 15, n = 3;

        (m + 1) / (n - 1) evaluates to 8

        (m + 1.0) / (n - 1.0) evaluates to 8.0

        m + 1 / n - 1 evaluates to 14

        m + 1.0 / n - 1 evaluates to 14.33333333333333
 


Assignment Command

    variable = expression;


Kinds of Expressions


Comments

                /* this is a comment */
 

                // another comment


Problem: Making Change (PP)

Given:
    Purchase price in cents
    Payment in cents

Assume change is made only in quarters, dimes, nickels, and pennies.

Provide the number of coins necessary for change using the least number of coins.

Example:

price = 126
payment = 210
change = 84

number of quarters = 84 / 25 = 3
remaining = 84 % 25 = 9

number of dimes = 9 / 10 = 0
remaining = 9 % 10 = 9

number of nickels = 9 / 5 = 1
number of pennies = 9 % 5 = 4

This example serves as the basis for writing the Java program to perform the calculation.

Java code:

public class Change

{

   public static void main(String[] args)

   {

      int price = 126; // "Input phase"

      int payment = 210;



      int change = payment - price; // Calculation phase



      int quarters = change / 25;

      int remaining = change % 25;



      int dimes = remaining / 10;

      remaining = remaining % 10;



      int nickels = remaining / 5;



      int pennies = remaining % 5;



      // Output phase

      System.out.println("Number of quarters = " + quarters);

      System.out.println("Number of dimes = " + dimes);

      System.out.println("Number of nickels = " + nickels);

      System.out.println("Number of pennies = " + pennies);

   }

}
Output:



Number of quarters = 3

Number of dimes    = 0

Number of nickels  = 1

Number of pennies  = 4

This program will be more useful when we can provide the price and payment as input, so that the program can be run on different sets of data.


Three Basic Components of a Programming Language

  1. Commands

    A command is an instruction that alters the state of the computer, such as changing memory or producing output.

    Assignment:        m = 5; k = 2 * m - 3;

    Output:                System.out.println("k = " + k);
     
  2. Expressions

    An expression is a phrase in a program that produces a value to be consumed one way or another.

    Literals

    Variables

    Operators        +, -, /, *, %
     
  3. Declarations

    A declaration is a statement that gives meaning to an identifier (a name), for example, a variable:

                type list-of-variables;

            Example of types: int, double, char, boolean, String


Example (of Expressions)


Java Code:

public class Expressions

{

   public static void main(String[] args)

   {

      int k, m, n;

      double x, y, z;

      String s, t, u;

      char c, d;



      m = 5;

      n = 13;

      k = n + 8 / 5;

      System.out.println("k = " + k); // k = 14



      x = 3.6;

      y = -10.5;

      z = x / 2 * y;

      System.out.println("z = " + z); // z = -18.9



      c = 'A';

      System.out.println("c = " + c); // c = A



      d = '&';

      System.out.println("d = " + d); // d = &



      s = "hello";

      t = "world";

      u = s + t;

      System.out.println("u = " + u); // u = helloworld



      u = s + "\n" + t;

      System.out.println("u = " + u); // u = hello

                                      // world

   }

}

Input

Input is relatively difficult to do in Java. A beginner needs to postpone doing input directly in Java.

We will use a special class, called TextInput, written by Ken Slonneger.

How to Use TextInput

  1. Create a TextInput object using:

    TextInput tin = new TextInput();    // can use any name for variable (tin in this example)
     
  2. Call one of these value-returning operations:

    integer_variable = tin.readInt();            returns an int

    double_variable = tin.readDouble();      returns a double
     

These input methods look for numbers separated by whitespace, typed by the user.

Whitespace is either a space, tab, or return.

The compiled code for the class can be found in the file text.jar. You'll need this file only if you download JCreator on your home PC.


If Commands

If Command: we can tell the computer to execute a section of code only when a given condition is true by using the if command.

        if (boolean-expression)
            command; // command executed if boolean-expression evaluates to true

 

or

        if (boolean-expression)
            command; // this command executed if boolean-expression evaluates to true
        else   
            command; // this command executed if boolean-expression evaluates to false
 


       Examples:

            if (degrees > 80)
                System.out.println("It is hot today.");

            (By convention we indent the command(s) that are subordinate to the if.)

           
            if (degrees > 80)
                System.out.println("It is hot today.");
            else
                System.out.println("It is a nice day today.");
 


Block Command

Block Command: we can tell the computer that a group of statements are to be executed as a result of a condition being true (or false). To do so we enclose those statements in curly braces.

        {   
                Sequence of declarations and commands
        }

Note that no semicolon follows this command.

What if we want more than one command with an if? Use a block command.

        if (boolean-expression)
        {
                Sequence of commands
        }

        Example:

        if (degrees > 80)
        {
            System.out.println("It is hot today.");
            System.out.println("Let's go swimming.");
        }
        else
        {
            System.out.println("It is a nice day today.");
            System.out.println("Let's have a picnic.");
        }


Boolean Expressions

    Relational operators produce boolean values



      ==          equal to    ("=" is assignment operator)

      !=          not equal to    

      <           less than

      >           greater than

      <=          less than or equal

      >=          greater than or equal

Check if an integer is even

Java Code:

public class Even

{

   public static void main(String[] args)

   {

      // prompt user for input

      System.out.print("Type an integer: ");



      // retrieve input from console

      TextInput input = new TextInput();

      int k = input.readInt();

   

      // determine if value read is even or odd

      if ((k % 2) == 0)

         System.out.println(k + " is even");

      else

         System.out.println(k + " is odd");

   }

}

How do we tell if a number is divisible by 5?

int m = 101;

if ((m % 5) == 0)
{
   System.out.println("m is divisible by 5.");
}
else
{
   System.out.println("m is not divisible by 5.");
}

Can use boolean variable in if command:

   int m = 18;

   boolean b;



   b = (m % 2) == 0;

   if (b) 

      System.out.println("m is even");


Can use literal in if command:

   if (true)         // always executes following command

      some command;

Boolean operators

|| (logical or), && (logical and), ! (logical not)
 

Expression Evaluates to
! true false
! false true
true && true true
true && false false
false && true false
false && false false
true || true true
true || false true
false || true true
false || false false

 


Nested if's

Test whether k is even. If it is, determine whether it is negative, zero, or positive.

Java Code:

public class EvenAnd

{

   public static void main(String[] args)

   {

      // prompt for input

      System.out.print("Input an integer: ");



      // retrieve input

      TextInput in = new TextInput();

      int k = in.readInt();



      // determine whether k is even AND negative, zero, or positive

      if ((k % 2) == 0)

      {

         System.out.print(k + " is even ");



         if (k < 0)

            System.out.println("and negative.");

         else if (k == 0)

            System.out.println("and zero.");

         else 

            System.out.println("and positive.");

      }

      else

         System.out.println(k + " is odd.");

   }

}

Nested if's can frequently be replaced by logical operators:

      if (((k % 2) == 0) && (k < 0))

         System.out.println(k + " is even and negative.");

      else if (((k % 2) == 0) && (k == 0))

         System.out.println(k + " is even and zero.");

      else if ((k % 2) == 0)

         System.out.println(k + " is even and positive.");

This code is not necessarily better.


BEWARE

   if (x = y) 



is normally an error: using assignment operator (=) instead of comparison operator (==).

What's wrong?

   if ((1 <= m) && (m <= 10))

      System.out.print("Hello ");

      System.out.println("world");

Operator Precedence

Highest -
!
unary minus
logical not
  *, /, % multiplicative operators
  +, - additive operators (binary)
  <. <=, >, >=  
  ==, !=  
  && logical and
  || logical or
Lowest = assignment

 


Rounding

Example:

Java Code:

public class Rounding

{

   public static void main(String[] args)

   {

      double x = 85.0, y = 307;

      System.out.println("x / y = " + x / y);

   }

}

prints:

x / y = 0.2768729641693811

If that's the number of decimal digits you want fine. But say you want only 3 digits after the decimal point.

Need to use a method:

    Math.rint(d)

that takes a double d and returns that double rounded to the nearest whole number (10.5 rounds to 10.0 (yes, that is right)). (Note: real numbers midway between two integers will round to the closest even integer, so 11.5 will round to 12.0.)

Math.rint(0.3423728) produces the value 0.0.

Solution: Move the decimal point three positions to the right (multiply by 1000.0), round the number, and then put the decimal point back in its proper position (by dividing by 1000.0). Specifically, do:

   double ans = Math.rint(1000.0 * d) / 1000.0;
 

In the example above do the following:

Java Code:

public class Rounding3

{

   public static void main(String[] args)

   {

      double x = 85.0, y = 307;

      System.out.println("x / y = " + Math.rint(1000.0 * (x / y)) / 1000.0);

   }

}

which prints:

x / y = 0.277

Strings

A String is an object in Java.  We will study objects at length later in the course.  For now we will use them without an in depth understanding of the details.

A sequence of characters between double quotes is a String in Java.  An example of a String literal is "Why did the chicken cross the road?".

We use escape characters to tell the compiler that there is a special character in a string.  If we want a String to contain a double quotation mark how can we do it?

\n  is how we insert a carriage return/line feed into a String.
\" is how we insert a double quotation mark in a String.
\\ is how we insert a backslash into a String.

Example use:

"This String contains several \"special\" characters.\nOne of those characters is a double backslash \"\\\\\"."

would print as:

This String contains several "special" characters.
One of those characters is a double backslash "\\".


Working with String Objects

String concatenation

String s = "Hello";

String t = "world";

String u = s + t; // u has the value "Helloworld"

 

s.substring(start,pastEnd)

If s is a string variable (or literal), the method call returns the substring of s consisting of characters in positions start, start+1, ... , pastEnd-1.

s.substring(0,1) // evaluates to "H"

u.substring(3,6) // evaluates to "low"

 

s.length()

If s is a string variable (or literal), the method call returns the number of characters in the string.

System.out.println("The String u has length of " + u.length());

// prints out "The String u has length of 10"

 

s.indexOf(substring)

If s is a string variable (or literal), the method call returns position of the first character in s where the entire substring occurs for the first time in s, returning -1 if the search fails.

System.out.println("The index of r in u is " + u.indexOf("r"));

// prints out "The index of r in u is 7"

 

s.lastIndexOf(substring)

Works the same way as indexOf(substring), except that it searches from the end of the String


String equality (BE VERY CAREFUL!)

String a = new String("String equality");

String b = "String equality";


Note: when a variable is assigned a String value, it is given a REFERENCE to the string object.

if (a == b) // NOT TRUE (fails because a and b are different references)

{

    System.out.println("a equals b");

}

Comparison between strings must be done with the operation "equals."

if (a.equals(b)) // IS TRUE

{

    System.out.println("a has the same characters in the same order as b");

}

else

{

    System.out.println("a and b do not have the same characters in the same order");

}

 

s.charAt()

To get the character at a certain position of a String we use charAt().  This method returns a char that is the character at the desired position of the String.

char ch = u.charAt(0); // Assigns the char value 'H' to variable ch;

Note that if we try to get a character at a position that does not exist we get an error.

 

s.toUpperCase()

We can convert all of the alphabetical characters of a string to uppercase with this method.

String s1 = u.toUpperCase(); // s1 now holds "HELLOWORLD"

 

s.toLowerCase()

We can convert all of the alphabetical characters of a  string to lowercase with this method.

String s2 = u.toLowerCase(); // s2 now holds "helloworld"

 

s.trim()

Sometimes we need to strip off any leading or trailing spaces from a string.  The trim() method does this for us.

String s3 = "  There are two leading spaces and two trailing spaces here  ";

System.out.println("s3 holds " + s3);

System.out.println("After we trim the spaces s3 holds " + s3.trim());

From Slonneger's TextInput class

Assume we have created the following text object using TextInput text = new TextInput();

String str = text.readLine();

Reads the string consisting of all characters typed up to but not including the return.

 

String word = text.readWord();

Reads next clump of letters and apostrophes.

 

String token = text.readToken();

Reads next clump of characters delimited by whitespace.


String Examples

Examples:

Java Code:

public class StringExample

{

   public static void main(String[] args)

   {

      // create text object

      TextInput tin = new TextInput();



      // prompt for input

      System.out.print("What is your name? ");



      // retrieve line of input

      String name = tin.readLine();



      // obtain first character

      char ch = name.charAt(0);



      // append a blank

      String initial = ch + " ";





      // convert to uppercase

      initial = initial.toUpperCase();



      // obtain first character 

      String temp1 = initial.substring(0,1);



      // obtain rest of characters

      String temp2 = name.substring(1,name.length());



      // remove spaces at front and back

      temp2 = temp2.trim();



      // output

      System.out.println("Hello " + temp1 + temp2);

   }

}

 

Problem: Print Date

Read three numbers, mm, dd, yyyy, and print the date in the common form: July 4, 2002.

Analysis:

    Use TextInput to read the numbers.

    Day and year are ready to be output immediately.

    Use a cascading if command to test the month and find the proper string.

Java Code:

public class Day

{

   public static void main(String[] args)

   {

      TextInput ti = new TextInput();



      System.out.print("Enter month (mm): ");

      int month = ti.readInt();



      System.out.print("Enter day (dd): ");

      int day = ti.readInt();



      System.out.print("Enter year (yyyy): ");

      int year = ti.readInt();



      String ans = "";



      if      (month == 1)  ans = "January"; 

      else if (month == 2)  ans = "February";

      else if (month == 3)  ans = "March";

      else if (month == 4)  ans = "April";

      else if (month == 5)  ans = "May";

      else if (month == 6)  ans = "June";

      else if (month == 7)  ans = "July";

      else if (month == 8)  ans = "August";

      else if (month == 9)  ans = "September";

      else if (month == 10) ans = "October";

      else if (month == 11) ans = "November";

      else if (month == 12) ans = "December";



      ans = ans + " " + day + ", " + year;



      System.out.println(ans);

   }

}

Note that we do not perform any input validation for this program. What happens if we input 25, 50, 2002?


Methods

A method is a group of commands that we want to be executed as a group. Sometimes we want that group of commands to calculate a value and return that value. Sometimes we don't want the method to return anything, just perform some tasks.

We can create our own methods to carry out our desired tasks. When we have written our programs so far, we have been putting commands into the body of the "main" method of the program.

To write a new method we must define it. We define a method by creating its header and its body. We include our new method definition between the opening and closing curly braces that define the class. If our class has more than just the main method, the order in which the methods appear inside the class is irrelevant.


Method headers

The parts of a method header are:


Method bodies

After the header has been declared we start the body. The body of a method is a block of code. We use the block command to delineate the start and stop of our method body.

Inside the body we can include almost any valid Java commands. We can declare variables, execute other methods, etc.

If in the header we said that the method will return a value of some type, then inside the body of the method we must include a "return" statement. The return statement returns the computed value to the statement that executed our method. When the return statement is executed, the compiler exits our method and resumes executing commands where it left off before executing our method.


Tracing the execution of a method

When the computer executes a program, it starts at the first statement in the main method and executes the commands in order after that.  When it encounters a call to a method, control passes to the header of that method. If there are any parameters declared in the header, then the compiler reserves memory for those variables and puts the data into those variables that was passed in from the calling statement. Then the body of the method is executed starting from the first statement in the body. When the last statement of the method is executed or a return statement is executed, control passes back to the statement that called the method.  See the text for a picture of this behavior.

Consider the following program:

Java Code:

public class Methods 

{ 

   public static void main(String args[]) 

   {

      String str1 = "I was declared inside main of the Methods class.";

      System.out.println("Inside the main method str1 has the value \"" + str1 + "\"");

      System.out.println("I am about to execute the method called printMessage.");

      printMessage();

      System.out.println("I am back inside the main method.");

      System.out.println("Inside the main method str1 has the value \"" + str1 + "\""); 

   }



   public static void printMessage()

   {

      System.out.println("I have entered method printMessage");

      String str1 = "I was declared inside method printMessage"; 

      System.out.println("Inside method printMessage str1 has the value \"" + str1 + "\"");

      System.out.println("I am about to leave the printMessage method");

   }

}

It produces the following output:
 

Inside the main method str1 has the value "I was declared inside main of the Methods class."

I am about to execute the method called printMessage.

I have entered method printMessage

Inside method printMessage str1 has the value "I was declared inside method printMessage

I am about to leave the printMessage method

I am back inside the main method.

Inside the main method str1 has the value "I was declared inside main of the Methods class."

Why use methods?

Creating methods gives us tools we can use to solve bigger problems. Consider the phone answering machine. It is making use of a "method" called "record sound."  The electrical engineers that invented the answering machine recognized that someone else developed a "method" to record sound waves.  All the engineers had to do was to feed that "method" the sound waves from the phone.  They used a component, or tool, that already existed so they did not have to reinvent the recording process. We can do the same. We can put together tools to accomplish complex tasks. We can use these tools over and over again in other programs without having to create the algorithm and translate it into Java every single time we want to solve the same problem. This is known as "code reuse."

If we want to execute the same set of code several times, we could write those lines of code for each time we want to execute them, or put them in a method and call the method each time we need that code executed. This makes for code that is easier to read and follow.  It also makes it easier to change the code later. If we need to change the process that is to be repeated several times, we would have to make the exact same change every place we wrote the code, or just change it once in the method. 

Putting code into a method allows for abstraction of a task. Consider the program to make change. First, we update it to read the price and payment from the keyboard.

Java Code:

public class Change1

{

   public static void main(String[] args)

   {

      // Declare our TextInput Object

      TextInput tin = new TextInput();



      // Prompt the user to enter the price

      System.out.print("What is the price? ");



      // Read the price from the keyboard

      int price = tin.readInt();



      // Prompt the user for the payment

      System.out.print("What is the payment? ");



      // Read the payment from the keyboard

      int payment = tin.readInt();



      // Now do our calculations like before.

      int change = payment - price;

      int quarters = change / 25;

      int remainder = change % 25;

      int dimes = remainder / 10;

      remainder = remainder % 10;

      int nickels = remainder / 5;

      remainder = remainder % 5;

      int pennies = remainder;



      // output result

      System.out.println("Quarters: " + quarters);

      System.out.println("Dimes: " + dimes);

      System.out.println("Nickels: " + nickels);

      System.out.println("Pennies: " + pennies);

      System.out.println("Total change: " + change);

   }

}

Let's now write the same program with methods.

Java Code:

public class Change2

{

   public static void main(String[] args)

   {

      // Get the price and payment.

      int price = getPrice();

      int payment = getPayment();



      // Now make sure they paid enough for the sale, and that the sale 

      // amount is a positive number.

      if (!validInput(price,payment))

      { 

         // If we made it here then the user gave us bad input. 

         // Print a message and exit the program.

         System.out.println("Invalid input. Please try again.");

         return;

      }



      // If we made it here then we have valid input. 



      // Calculate the amount of change to give.

      int change = payment - price;



      // Now get the number of quarters to return .

      int quarters = getNumCoins(25,change);



      // Compute remaining change to give.

      int remainder = change % 25;



      // Now get the number of dimes.

      int dimes = getNumCoins(10,remainder);



      // Compute remaining change to give.

      remainder = remainder % 10;



      // Get the number of nickels.

      int nickels = getNumCoins(5,remainder);



      // Compute remaining change to give.

      remainder = remainder % 5;



      // The remaining change to give must be given in pennies.

      int pennies = remainder;



      // Print the results.

      printResults(quarters, dimes, nickels, pennies, change);

   }



   public static int getPrice()

   {

      // Declare a TextInput Object.

      TextInput tin = new TextInput();



      // Prompt the user to enter the price.

      System.out.print("What is the price? ");



      // Read and return the price from the keyboard.

      return tin.readInt();

   } 



   public static int getPayment()

   {

      // Declare a TextInput Object.

      TextInput tin = new TextInput();



      // Prompt the user to enter the payment.

      System.out.print("What is the payment? ");



      // Read and return the payment from the keyboard.

      return tin.readInt();

   }



   public static boolean validInput(int price, int payment)

   {

      if (price < 1)

      {

         // We don't give items away so price must be at least 1

         return false;

      }



      // If we made it here then the price must be valid. 

      // Now make sure that the payment is at least as high

      // as the price.

      if (payment < price)

      {

         return false;

      }



      // If we made it here then the input must be valid

      return true;

   }



   public static int getNumCoins(int value, int changeLeft)

   {

      return changeLeft / value;

   }



   public static void printResults(int quarters, int dimes, int nickels, int pennies, int change)

   {

      System.out.println("Quarters: " + quarters);

      System.out.println(" Dimes: " + dimes);

      System.out.println(" Nickels: " + nickels);

      System.out.println(" Pennies: " + pennies);

      System.out.println("Total change: " + change);

   }

}


Concepts to learn from the previous example


Object-Oriented Programming (OOP)

Change the focus of programming from the program units to the data that need to be manipulated.

Each data item has its own type.

        5  is of type int

        2.63  is of type double

        ‘H’  is of type char

        false is of type boolean

        "hello" is of type String
 

OOP allows us to define new types of data:

Some new classes that might be useful:

        Date                 Domino            Employee

        Coin                 Student            Point

        Die                   Button

An object is an instance (a specimen) of a class.


An Object Contains

Example (outline only)

class Die

      Possible fields

      Possible behavior
 

These fields and behaviors are defined in a class definition.

class Die
{
      // data declarations and method declarations
}
 

Such a class definition creates a new kind or type of data, namely Die objects.


Create Die Objects

Use the new operator and specify initial information

Die d1, d2;       // declares variables of type Die

d1 = new Die(6, Color.blue);

d2 = new Die(20, Color.red);
 

Color.blue and Color.red are two of the thirteen color constants provided in Java.
 

Suppose roll is a method defined inside the Die class with the syntax:

int roll()
 

Using the roll method:

     int m = d1.roll();         // returns a value 1…6

      int n = d2.roll();          // returns a value 1…20
 

Syntax of a call to a method belonging to an object:

      objectReference.methodName(parameters)
 

Method may be a function or a procedure.

Example of a procedure:

      d1.setColor(Color.orange); // changes color to orange


Two Kinds of Methods in Classes

                instance methods  and  class methods
 

                d1.getColor();  // returns the current color of the d1 Die

                d2.setColor(Color.white);  // tells the d2 Die to change its color


String Class (predefined in Java)

Constructors are a kind of instance method automatically called when an object is created.

      String s1 = new String();            // empty string

      String s2 = new String("herky");

      String s3 = "herky";                    // exception: no new

      String s4 = s2;


The String class has a constructor with no parameters and one with a single parameter.


String Instance Methods

     s1.length()                    returns 0

        s2.length()                    returns 5

        s2.indexOf("ky")          returns 3

        s2.indexOf("hk")          returns -1

        s2.substring(1,4)          returns "erk"

        s2.concat(s3)               returns "herkyherky"

        s2.equals(s3)               returns true

        s2 == s3                      returns false

        s2 == s4                      returns true

        s2.charAt(1)                 returns 'e'

        String str = "      152    ";

        str.trim()                       returns "152"


Class Methods

                String.valueOf(5723);  // returns "5723"


Other Class Methods

        Math.sqrt(2)                       returns 1.4142135

        Math.random()                    returns a random double, 0≤d<1

        Math.rint(7.82)                   returns 8.0

        Math.abs(-13)                     returns 13

        Integer.parseInt("5723")     returns 5723 as an int


Variables and Values

Values

            Primitive data items:

                        int, double, char, boolean

            Objects:

                        String, Point, Date, Die

Variables

Symbols that name memory locations; these locations may contain values.

Examples:

            int k;                                   // a variable

            k = 5;                                  // put a value in k’s location

            k = k + 2;                            // change value in k's location

            System.out.println(5);          // 5

            System.out.println("k");        // k

            System.out.println(k);           // 7

 

Compare    if (x == k) …      with    if (x == 'k') …

 

TextInput ti = new TextInput();

String ans = ti.readWord();

String yes = "no";

Compare
     if (ans.equals(yes)) …     with    if (ans.equals("yes")) …


Defining Methods

Java has two kinds of methods with overlap between the kinds.
 

Functions

Procedures


Class Methods


Instance Methods

Clarification

Since we are not defining our own objects yet, we must concentrate on class methods (Procedural Programming)

If we want to define an operation on String objects, it must be a class method since we cannot get into the class definition for the String class (it was written by Sun several years ago).
 


Largest of Three

Write a method that takes three integers as parameters and returns the largest of the three.

Java Code:

public class largest3

{

   static int largest(int n1, int n2, int n3)

   {

      if (n1 > n2)

      {

         if (n1 > n3)

            return n1;

         else 

            return n3;

      }

      else 

      if (n2 > n3)

         return n2;

      else 

         return n3;

   }

   

   public static void main(String[] args)

   {

      int largestOfThree = largest(2,22,12);

      System.out.println("The largest of 2, 22, and 12 is " + largestOfThree);

   }

}

Testing for an Empty String

The method isEmpty will take a String as a parameter and tell whether that string is empty, meaning that it returns true or false.

Java code:

public class IsEmptyTest

{

   static boolean isEmpty(String s)

   {

      boolean result = (s.length() == 0);

      return result;

   }



   public static void main(String[] args)

   {

      System.out.println("Is \" \" an empty string? " + isEmpty(" "));

      System.out.println("Is \"\" an empty string? " + isEmpty(""));

   }

}

Alternative definition

Java Code:

public class IsEmptyTest2

{

   static boolean isEmpty(String s)

   {

     return s.equals("");

   }



   public static void main(String[] args)

   {

      System.out.println("Is \" \" an empty string? " + isEmpty(" "));

      System.out.println("Is \"\" an empty string? " + isEmpty(""));

   }

}

Calling the isEmpty method, using strings read from the console.

Java Code:          

public class IsEmptyTest3

{

   static boolean isEmpty(String s)

   {

     return s.equals("");

   }



   public static void main(String[] args)

   {

      TextInput text = new TextInput();

      

      System.out.print("Enter a string: ");

      String str = text.readLine();

      

      if (isEmpty(str))

         System.out.println("The string is empty.");

      else

         System.out.println("The string has characters.");

   }

}

Note:  We cannot make isEmpty an instance method because we cannot add code inside the String class.

Class methods act as utility operations working outside of the realm of objects, although they may take objects as parameters.


A Procedure to Print the Last Three Digits of a Positive Integer

Write a method that takes a positive integer as a parameter and prints the last three digits, one to a line, unit’s digit first. Do nothing if the number is not positive.  

Java Code:       

public class printDigitsTest

{

   static void printDigits(int num)

   {

      if (num > 0)

      {

         int units = num % 10;

         int tens = (num / 10) % 10;

         int hundreds = (num / 100) % 10;

         System.out.println(units);

         System.out.println(tens);

         System.out.println(hundreds);

      }

   }



   public static void main(String[] args)

   {

      System.out.print("Enter a number: ");

      

      int m = (new TextInput()).readInt();

      

      printDigits(m);

   }

}

Note that we create one TextInput object and use it immediately.

Since it is not assigned to a variable, it can only be used once.

Parentheses are required because the dot has higher precedence that the new operator.


Month Strings

Write a method that takes an integer as a parameter and returns a String representing the month specified by the number, 1≤ month ≤12.

To convert the month integer into a String, create a String, called months, containing all the month names with each name taking 10 characters.

Then select the appropriate 10-character substring for the month desired.

For example, the 1st month will lie in character positions 0 to 9, the 2nd month will lie in character positions 10 to 19, and the 5th month will lie in character positions 40 to 49.

Use the instance method trim() to remove the extra spaces.

Java Code:

public class monthStringTest

{

   static String monthString(int month)

   {

      String months =

         "January   February  March     April     " +

         "May       June      July      August    " +

         "September October   November  December  ";

         

      int m = month - 1; // 0 <= m <= 11

      

      String s = months.substring(10 * m, 10 * m +10).trim();

      

      return s;

   }

   

   public static void main(String[] args)

   {

      TextInput text = new TextInput();

      

      System.out.print("Enter the number of a month between 1 and 12: ");

      

      System.out.println(monthString(text.readInt()));

   }

}

Observe that this method is a function.


Expressions with Side Effects

The purpose of an expression is to produce a value.

In addition, some expressions may have side effects.

Side effect:            Change in the value of a variable.

                                Output to the display screen.


Assignment

                        var = expr;

Normally acts as a command.

But it may also serve as an expression; its value is the value assigned to the variable on the left.

            m = 5 + (n = 3);                                            // n get 3 and m gets 8

            if ((m = m + 6) > 0) …                                   // m gets 14

This usage is poor programming style.


Other Assignment Operators (15 of them)

         m += 5;                       means               m = m+5;

         k *= 2;                       means               k = k*2;

         x /= 10;                     means               x = x/10;

         p &&= q;                    means               p = p && q;

         n >>>= 2;                    means   n = n >>> 2;        // shift n, 2 bits to right
 


Increment and Decrement Expressions

These expressions may be used as commands:

            m++;                  // has the effect of m = m + 1;

            k--;                   // has the effect of k = k - 1;


Equivalent Commands

            k = k + 1;                                                           m = m – 1;

            ++k;                                                                  --m;

            k++;                                                                  m--;

            k += 1;                                                               m –= 1;


Difference between ++k and k++

Preincrement

When ++k occurs in a larger expression, the value of k is augmented before it is accessed (used).

            k = 5;

            m = ++k;            // k gets 6, m gets 6

Postincrement

For k++, the value is accessed before k is augmented, and that previous value is used in the expression.

            k = 5;

            m = k++;            // k gets 6, m gets 5

These expressions can lead to obscure code:

            m = 5;                                                         m = 5;

            n = m++ * m;                                                n = m * m++;

            // n gets value 30                                       // n gets value 25


Recommendations


Tracing Method Calls

Java Code:

public class Trace

{

   public static void main(String [] args) 

   {

      System.out.println("Starting main");

      int k = 20;

      

      one(k);

      System.out.println("Back from one");

      

      k = 5;

      one(k);

      System.out.println("Back from one again");

      

      System.out.println("Done with k = " + k); 

   }

   

   static void one(int m)

   {

      System.out.println("Entering one with m = " + m);

      int ans = 1;

      m = m * m;

      if (m < 100)

         ans = two(m, 1.2);

      System.out.println("ans = " + ans);

      System.out.println("Leaving one with m = " + m);

   }

   

   static int two(double x, double y)

   {

      System.out.println("Entering two");

      double z = x * x + y * y;

      System.out.println("Leaving two with z = " + z);

      return (int)z;

   }

}

/*************************** Here's the output

Starting main

Entering one with m = 20

ans = 1

Leaving one with m = 400

Back from one

Entering one with m = 5

Entering two

Leaving two with z = 626.44

ans = 626

Leaving one with m = 25

Back from one again

Done with k = 5

***************************/


Dangling Else Problem

Consider the code:

         if (m > 0)

         if (n > 0)

                 System.out.println("m and n are positive");

      else

        System.out.println("m is <= 0");

Note ambiguity: To which if does else belong?

An else clause always belongs to the if of the preceding command (the closest pending if).

Indenting and logic are incorrect.

Try m = 10 and n = -3.

 

Be careful to indent correctly.

Use braces (a block command) to group commands.

         if (m > 0)

         {

            if (n > 0)

               System.out.println("m and n are positive");

         } 

         else

         System.out.println("m is <= 0");


Generating random numbers

In simulation problems we frequently want to create an integer in some given range randomly.

Problem

            Select a random number between 1 and 100.

Solution

  1. double d = Math.random();

    0 <= d < 1

  2. Number of possibilities (=100 in the following example) becomes a multiplier:

    0 <= 100 * d < 100

  3. Truncate to an integer using a cast:

    (int) (100 * d) is one of the values 0, 1, 2, ..., 0=98, 99

  4. Add the first value in the range:

    1 + (int) (100 * d) is one of the values 1, 2, 3, ..., 99, 100

Example:

Java Code:

public class GenerateRandom

{

   public static void main(String[] args)

   {

      double d = Math.random(); // 0 <= d < 1

      

      int num = (int) (100 * d); // 0 <= num < 100

      

      num = num + 1; // 1 <= num <= 100

      

      System.out.println("Random number between 1 and 100 is " + num);

   }

}

Using Methods to solve problems

Write a program that will play "Guess my number" with the user.  The computer will pick a number between 1 and 100 inclusive.  Then the user will try to guess the number that the computer picked.  The computer displays a message to the user stating whether the computer's number is higher or lower.  The user has 10 tries to guess the number.  

How do we go about solving this problem?  Start by writing an algorithm.

  1. Print the rules of the game.
  2. Generate random number.
  3. Play turn 1.
  4. if (win) exit program
  5. Play turn 2.
  6. if (win) exit program
  7. Play turn 3.
  8. if (win) exit program
  9. Play turn 4.
  10. if (win) exit program
  11. Play turn 5.
  12. if (win) exit program
  13. Play turn 6.
  14. if (win) exit program
  15. Play turn 7.
  16. if (win) exit program
  17. Play turn 8.
  18. if (win) exit program
  19. Play turn 9
  20. if (win) exit program
  21. Play turn 10.

Each step is a task.  Let's make a method for each task.

  1. printRules()
  2. number = generateNumber()
  3. playTurn(1)
  4. if (win) exit program
  5. playTurn(2)
  6. if (win) exit program
  7. playTurn(3)
  8. if (win) exit program
  9. playTurn(4)
  10. if (win) exit program
  11. playTurn(5)
  12. if (win) exit program
  13. playTurn(6)
  14. if (win) exit program
  15. playTurn(7)
  16. if (win) exit program
  17. playTurn(8)
  18. if (win) exit program
  19. playTurn(9)
  20. if (win) exit program
  21. playTurn(10)

Will this algorithm solve our problem?  It will if we define the methods.

/*
   The printRules() method does not receive any input.It just prints some lines 
   to the screen.
*/
public static void printRules()
{
   // The body will contain just some print statements. 
}

/*
  The generateNumber() method will not need any inputs.
  It will generate a random int between 1 and 100
  inclusive and return that int.
*/
public static int generateNumber()
{
  return (int)(Math.random() * 100) + 1;
}

/*
  The playTurn() method receives a number that says which 
  turn we are playing.  We will need this method to return
  true or false telling the caller whether the player won 
  the game or not.

  This method prompts the player for their guess.  It reads the
  input and validates it.  If the input is not valid a message is
  displayed and the method returns false.  If the input is valid 
  then this method determines if the player's guess is correct,
  too high, or too low.  A message is displayed accordingly.  If
  the guess was the correct number the method returns true, 
  otherwise false.
*/
 

public static boolean playTurn(int turn)
{
  // Prompt player for their guess and capture it.
  int guess = getGuess(turn);

  // validate the guess
  boolean isValid = validateInput(guess);
  
  // Handle the case where the input is invalid.
  if (!isValid)
  {
    System.out.println("Please guess a number between 1 and 100 inclusive");
    return false;
  }  

  // If we made it here then the input was valid so compare it to 
  // the correct number
  if (guess == number)
  {  
    System.out.println("Congratulations! You win!");
    return true;
  }
  else
  {
    // Print proper message and return false
    if (number < guess)
    {
      System.out.println("The correct number is lower");
    }   
    else
    {
      System.out.println("The correct number is higher"); 
    }
    return false;
  }
}

This method calls some helper methods to help him get his job done.  Let's define those helper methods.


Complete program

Java Code:

/*



Class GuessMyNumber 



  This class plays a game with a user.  The program 

  generates a random number between 1 and 100.  The player 

  then has 10 turns to guess the number.  The program prompts

  the player for their guess.  The player's guess is 

  validated.  If the guess is not valid a message is 

  displayed and the turn is over.  If the guess is valid

  then a message is displayed stating whether the correct

  number is higher, lower, or exactly correct.  If the 

  player guesses the number within 10 turns they win and the 

  game ends.



Inputs:  There are no command line inputs to this program.

         The user is prompted to enter integers.



Outputs: Messages are displayed to the screen.



History: 06/17/02 Jeff LeBeau.



******************************************************/



public class GuessMyNumber

{

   static int number;

   

   public static void main(String[] args)

   {

      // Generate the number

      number = generateNumber();



      if (playTurn(1)) return;

      if (playTurn(2)) return;

      if (playTurn(3)) return;

      if (playTurn(4)) return;

      if (playTurn(5)) return;

      if (playTurn(6)) return;

      if (playTurn(7)) return;

      if (playTurn(8)) return;

      if (playTurn(9)) return;

      if (!playTurn(10)) 

      {

         System.out.println("Sorry! You lose.");

      }

   }



   /*******************************************************

    The printRules method does not receive any input. It 

    just prints some lines to the screen

   *******************************************************/

   public static void printRules()

   {

      System.out.println("Welcome to Guess My Number");

      System.out.println("I have picked a number between 1 and 100 inclusive.");

      System.out.println("You must try to guess my number in 10 turns or less.\n\n"); 

   }



   /*******************************************************

    The generateNumber() method will not need any inputs.

    It will generate a random int between 1 and 100

    inclusive and return that int.

   *******************************************************/

   public static int generateNumber()

   {

      return (int)(Math.random() * 100) + 1;

   }



   /*******************************************************

    The playTurn() method receives a number that says which 

    turn we are playing.  We will need this method to return

    true or false telling the caller whether the player won 

    the game.

  

    This method prompts the player for their guess.  It reads

    the input and validates it.  If the input is not valid a

    message is displayed and the method returns false.  If 

    the input is valid then this method determines if the 

    player's guess is correct, too high, or too low.  A message

    is displayed accordingly.  If the guess was the correct 

    number the method returns true, otherwise false.

   *******************************************************/

   public static boolean playTurn(int turn)

   {

      // Prompt player for their guess and capture it.

      int guess = getGuess(turn);

   

      // validate the guess

      boolean isValid = validateInput(guess);

    

      // Handle the case where the input is invalid.

      if (!isValid)

      {

         System.out.println("Please guess a number between 1 and 100 inclusive");

         return false;

      }

  

      // If we made it here then the input was valid so compare it to 

      // the correct number

      if (guess == number)

      {  

         System.out.println("Congratulations! You win!");

         return true;

      }

      else

      {

         // Print proper message and return false

         if (number < guess)

         {

            System.out.println("The correct number is lower");

         }   

         else

         {

            System.out.println("The correct number is higher"); 

         }

         return false;

       }

   }



   /*******************************************************

    The getGuess() method receives 1 parameter as input.

    That is the current turn number.

  

    It prompts the player for a number between 1 and 100

    and returns the response from the user as an int.

   *******************************************************/

   public static int getGuess(int turn)

   {

     // We will need a TextInput object to read in the number

     TextInput tin = new TextInput();

  

     System.out.print("Turn " + turn + ": Enter an integer between 1 and 100 inclusive. ");

     return tin.readInt();

   }



   /*******************************************************

    The validateInput method receives the guess that the 

    player entered and returns true if the number lies 

    between 1 and 100 inclusive, false otherwise.

   *******************************************************/

   public static boolean validateInput(int myGuess)

   {

      if ((myGuess < 1) || (myGuess > 100))

      {

         return false;

      }

      else

      {

         return true;

      }

   }

}

Writing Numerals in English

When writing a check we need to express the number with English words.

Write a program that reads an integer between 0 and 999 and prints the corresponding English words.

Sample execution:

Enter an integer between 0 and 999: 567

five hundred sixty-seven

Analysis:

Digits in 567:       5 is hundred’s digit
                            6 is ten’s digit
                            7 is unit’s digit.
 

The hundreds and most of the units are handled the same way, using the strings "one", "two", …, "nine".
 

Most of the tens digits are represented by the strings "twenty", "thirty", …, "ninety". Note, however, that this ten word is followed by a hyphen only if the units digit is nonzero.

 

Exception:             Numbers from 10 to 19 have special words, "ten", "eleven", …, "nineteen".

We use methods to convert the digits to the appropriate words.

 

The main method:

Java Code:

public class Numbers

{

   static String units(int m)

   {

      if (m == 0) return "zero";

      if (m == 1) return "one";

      if (m == 2) return "two";

      if (m == 3) return "three";

      if (m == 4) return "four";

      if (m == 5) return "five";

      if (m == 6) return "six";

      if (m == 7) return "seven";

      if (m == 8) return "eight";

      if (m == 9) return "nine";

      return "Invalid units";

   }

   

   static String tens(int m)

   {

      if (m == 2) return "twenty";

      if (m == 3) return "thirty";

      if (m == 4) return "forty";

      if (m == 5) return "fifty";

      if (m == 6) return "sixty";

      if (m == 7) return "seventy";

      if (m == 8) return "eighty";

      if (m == 9) return "ninety";

      return "Invalid tens";

   }

   

   static String teens(int m)

   {

      if (m == 0) return "ten";

      if (m == 1) return "eleven";

      if (m == 2) return "twelve";

      if (m == 3) return "thirteen";

      if (m == 4) return "fourteen";

      if (m == 5) return "fifteen";

      if (m == 6) return "sixteen";

      if (m == 7) return "seventeen";

      if (m == 8) return "eighteen";

      if (m == 9) return "nineteen";

      return "Invalid teens";

   }

   

   public static void main(String[] args)

   {

      TextInput textIn = new TextInput();

      

      System.out.print("Enter an integer between 0 and 999: ");

      int num = textIn.readInt();

      

      if ((num < 0) || (num > 999))

      {

         System.out.println("Number not between 0 and 999");

         return;

      }

      

      int unitsDigit = num % 10;

      

      int q = num / 10;

      

      int tensDigit = q % 10;

      

      q = q / 10;

      

      int hundredsDigit = q % 10;

      

      String resultString = "";

      

      if (hundredsDigit > 0)

         resultString = resultString + units(hundredsDigit) + " hundred ";

         

      if ((2 <= tensDigit) && (tensDigit <= 9))

      {

         resultString = resultString + tens(tensDigit);

         

         if (unitsDigit > 0)

            resultString = resultString + "-" + units(unitsDigit);

      }

      else

      if (tensDigit == 1)

      {

         resultString = resultString + teens(unitsDigit);

      }

      else

      if ((tensDigit == 0) && ((unitsDigit > 0) || (hundredsDigit == 0)))

      {

         resultString = resultString + units(unitsDigit);

      }

      

      System.out.println(resultString);

   }

}

Output

Enter an integer between 0 and 999: 908

nine hundred eight

 

Enter an integer between 0 and 999: 1

one

 

Enter an integer between 0 and 999: 519

five hundred nineteen

 

Enter an integer between 0 and 999: 0

zero


Review for Exam #1