Unit 3 sample programs

  1. Subroutines (return an Integer)
  2. Subroutines (return an String)
  3. Applets: drawString
  4. Applets: Graphics
  5. Applets: Dice
  6. Applets: GUI
  7. Simple Game


Illustrating Subroutines (return an Integer) Ass3s2p8.java        

Write a method int sumDiv( int n) that will return the sum of the divisors of n and write a program to test it. Include in your sum the number 1, but not the number n itself. Note that sumDiv(10) = 1+2+5 = 8, sumDiv(25) = 1+5 = 6, and sumDiv(103) = 1. If n<1 return 0


// The "Ass3s2p8" class.
import java.awt.*;
import hsa.Console;

public class Ass3s2p8
{
    static Console cs;

    public static void main (String [] args)
    {
     cs = new Console ();
     cs.println ("Printing the next 20 numbers with their sums of divisors\n");
     cs.print ("enter an integer to start: ");
     int start = cs.readInt ();
     for (int num = start ; num < start + 20 ; num++)
     {
         cs.print ("          sum of divisors of ");
         cs.print (num, 5);
         cs.print ("   is ");
         cs.println (sumDiv (num), 5);
     }
    } // main method


    public static int sumDiv (int n)
    {
     if (n < 1)
         return 0;
     int sum = 1;
     for (int d = 2 ; d <= n / 2 ; d++)
         if (n % d == 0)
          sum += d;
     return sum;
    } //end sumdiv
} // Ass3s2p8 class




Illustrating Subroutines (return an String): Ass3s2p18.java        

Write a method String monthName (int m) that returns the name of the month . monthName(5) would return "May". Any invalid input should return a string containing one blank character (" "). Write a program that tests the method.


// The "Ass3s2p18" class.
import java.awt.*;
import hsa.Console;

public class Ass3s2p18
{
    static Console cs;

    public static void main (String [] args)
    {
     cs = new Console ();
     cs.println ("test the name of the month:");
     cs.print ("enter a number, any invalid month number to stop: ");
     int m = cs.readInt ();
     String name = monthName (m);
     while (!name.equals (" "))
     {
         cs.println (m + " stands for the month of " + name);
         cs.print ("enter a number, any invalid month number to stop: ");
         m = cs.readInt ();
         name = monthName (m);
     }
    } // main method


    public static String monthName (int n)
    {
     String month [] = {"January", "February", "March", "April", "May", "June",
         "July", "August", "September", "October", "November", "December"};
     if (n < 1 || n > 12)
         return " ";
     return month [n - 1];
    } //end monthName
} // Ass3s2p18 class



Illustrating Applets: drawString: Ass3s4p1.java        

Write a program that will print your school's name and address in the middle of a 500x300 applet.

When you have written the file and tested it, locate the HTML file of the same name and run it in this browser


/ The "Ass3s4p1" class.
import java.applet.*;
import java.awt.*;

public class Ass3s4p1 extends Applet
{
    Font f;

    public void init ()
    {
     setBackground (Color.white);
    } // init method


    public void paint (Graphics g)
    {
     f = new Font ("TimesRoman", Font.BOLD, 36);
     g.setFont (f);
     g.setColor (Color.gray);
     g.drawString ("Albert Campbell C.I.", 22, 102);
     g.setColor (Color.blue);
     g.drawString ("Albert Campbell C.I.", 20, 100);
     g.setColor (Color.red);
     f = new Font ("TimesRoman", Font.PLAIN, 24);
     g.setFont (f);
     g.drawString ("1550 Sandhurst Circle", 20, 170);
     g.drawString ("Toronto, ON", 20, 250);
    } // paint method
} // Ass3s4p1 class



Illustrating Applets: Graphics: Ass3s4p7.java        

Write a program that lets you draw the following or similar shape:


// The "Ass3s4p7" class.
import java.applet.*;
import java.awt.*;

public class Ass3s4p7 extends Applet
{
    Font f;

    public void init ()
    {
     setBackground (Color.white);
    } // end init method


    public void paint (Graphics g)
    {
     f = new Font ("Times New Roman", Font.BOLD, 12);
     g.setFont (f);
     g.setColor (Color.blue);
     g.drawString ("Sleepy Face", 150, 30);
     // yellow face with black outline
     g.setColor (Color.yellow);
     g.fillOval (100, 100, 180, 180);
     g.setColor (Color.black);
     g.drawOval (100, 100, 180, 180);
     // orange eyes with black  outline
     g.setColor (Color.orange);
     g.fillOval (130, 140, 50, 50);
     g.fillOval (200, 140, 50, 50);
     g.setColor (Color.black);
     g.drawOval (130, 140, 50, 50);
     g.drawOval (200, 140, 50, 50);
     // red nose
     g.setColor (Color.red);
     g.fillOval (182, 200, 16, 16);
     g.setColor (Color.black);
     g.drawOval (182, 200, 16, 16);
     // mouth and eye lines
     g.drawLine (150, 240, 230, 240);
     g.drawLine (130, 170, 180, 170);
     g.drawLine (200, 170, 250, 170);


    } // end paint method
} // Ass3s4p7 class



Illustrating Applets: Dice: Ass3s4p12.java        

Write a method void oneDie(int x, int y, int value) that will draw a die with the upper left corner at position (x,y) and showing the value "value" then test the method by randomly generating 2 dice in the middle of the field, together with their sum, using one red and one blue die


// The "Ass3s4p12" class.
import java.applet.*;
import java.awt.*;

public class Ass3s4p12 extends Applet
{

    public void init ()
    {
     setBackground (Color.white);
    } // end init method


    public void paint (Graphics g)
    {
     Font f = new Font ("Times New Roman", Font.BOLD, 12);
     g.setFont (f);
     g.setColor (Color.blue);
     g.drawString ("Two random dice", 150, 30);
     die (g, 100, 100, randomDieNumber (), Color.blue);
     die (g, 230, 100, randomDieNumber (), Color.red);
    } // end paint



    public void die (Graphics gr, int x, int y, int val, Color c)
    {
     gr.setColor (c);
     gr.fillRect (x, y, 58, 58);
     gr.setColor (Color.black);
     gr.drawRect (x, y, 58, 58);
     gr.setColor (Color.white);
     if (val > 1) // upper left and lower right for 2,3,4,5,6
     {
         gr.setColor (Color.white);
         gr.fillOval (x + 4, y + 4, 14, 14);
         gr.fillOval (x + 40, y + 40, 14, 14);
         gr.setColor (Color.black);
         gr.drawOval (x + 4, y + 4, 14, 14);
         gr.drawOval (x + 40, y + 40, 14, 14);
     }
     if (val > 3) // upper right and lower left for 4,5,6
     {
         gr.setColor (Color.white);
         gr.fillOval (x + 40, y + 4, 14, 14);
         gr.fillOval (x + 4, y + 40, 14, 14);
         gr.setColor (Color.black);
         gr.drawOval (x + 40, y + 4, 14, 14);
         gr.drawOval (x + 4, y + 40, 14, 14);
     }
     if (val % 2 == 1) // center for odds, i.e. 1,3,5
     {
         gr.setColor (Color.white);
         gr.fillOval (x + 22, y + 22, 14, 14);
         gr.setColor (Color.black);
         gr.drawOval (x + 22, y + 22, 14, 14);
     }
     if (val == 6) // left and right center for 6
     {
         gr.setColor (Color.white);
         gr.fillOval (x + 4, y + 22, 14, 14);
         gr.fillOval (x + 40, y + 22, 14, 14);
         gr.setColor (Color.black);
         gr.drawOval (x + 4, y + 22, 14, 14);
         gr.drawOval (x + 40, y + 22, 14, 14);
     }
    } //end die


    public int randomDieNumber ()
    {
     return (int) (Math.random () * 6 + 1);
    } // end random number
} // Ass3s4p12 class




Illustrating Applets: GUI: Ass3s4p24.java        

Use a label and three textboxes in a program that lets you enter the three sides of a triangle and that prints out (if the three sides can form a triangle) the values (in degree measure) of the three corresponding angles, using the cosine law The angle A, (contained by sides b,c and opposite side a) can be found using the formula:

where C must next be converted to degree measure: A *= 57.2958. the java function Math.acos( ) corresponds to cos-1 ( )
Create the method double cosLawSSS(double b, double a, double c) that will return the angle opposite side a (the middle parameter)

// The "Ass3s4p24" class.
// preferred size of applet: 400 x 200
import java.applet.*;
import java.awt.*;
import java.awt.event.*;

public class Ass3s4p24 extends Applet implements ActionListener
{
    Font f = new Font ("TimesRoman", Font.PLAIN, 14);
    TextField a_in = new TextField (10);
    TextField b_in = new TextField (10);
    TextField c_in = new TextField (10);
    Label instructions = new Label
	("Enter three integers: representing the sides of a triangle");
    int a = 10;
    int b = 10;
    int c = 10;

    public void init ()
    {
      setBackground (Color.white);
      add (instructions);
      a_in.addActionListener (this);
      b_in.addActionListener (this);
      c_in.addActionListener (this);
      add (a_in);
      add (b_in);
      add (c_in);
      a_in.setText ("10");
      b_in.setText ("10");
      c_in.setText ("10");
    } // end init


    public void actionPerformed (ActionEvent evt)
    {
      try
        {
            a = Integer.parseInt (a_in.getText ());
            b = Integer.parseInt (b_in.getText ());
            c = Integer.parseInt (c_in.getText ());
        }
       catch (NumberFormatException e)
        {
        }
	   repaint ();
     } // end actionPerformed

    public void paint (Graphics g)
    {
      g.setFont (f);
      g.setColor (Color.blue);
      if (cosLawSSS (a, b, c) == -1)
          g.drawString ("these numbers can't form a triangle", 10, 100);
      else
      {
          g.drawString ("the angle opposite " + a + " is "
      	    + roundTo2 (cosLawSSS (b, a, c)), 130, 100);
          g.drawString ("the angle opposite " + b + " is "
      	    + roundTo2 (cosLawSSS (a, b, c)), 130, 116);
          g.drawString ("the angle opposite " + c + " is "
      	    + roundTo2 (cosLawSSS (b, c, a)), 130, 132);
      }
    }// end paint


    public double cosLawSSS (double b, double a, double c)
    {
      double s = (a + b + c) / 2.0;
      if (s <= a || s < b || s < c)
          return -1;
      else
      {
          double fraction = (b * b + c * c - a * a) / b / c / 2.0;
          return Math.acos (fraction) * 57.295828;
      }
    } //end cosLaWSSS


    public double roundTo2 (double x)
    {
      return Math.round (100 * x) / 100.0;
    } //end roundTo2
} // Ass3s4p24 class





Illustrating Simple Game: Ass3s4p28.java        

Write a program that uses 3 radio buttons called "rock", "scissors", "paper" and a button called "GO". Write a program where you play the computer. When you make a choice , the computer too makes a random choice. When you press "GO" the computer will display the result. Note that : Rock wins over Scissors; Scissors wins over Paper and Paper wins over Rock. Choosing the same implement results in a draw.

// The "Ass3s4p28" class.
// preferred size of applet: 300 x 200

import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;

public class Ass3s4p28 extends Applet implements ActionListener
{
    Font f = new Font ("TimesRoman", Font.PLAIN, 18);
    Button go = new Button ("GO");
    
    CheckboxGroup choice = new CheckboxGroup ();
    Checkbox rock = new Checkbox ("Rock", choice, true);
    Checkbox scissors = new Checkbox ("Scissors", choice, false);
    Checkbox paper = new Checkbox ("Paper", choice, false);

    int r = 0, s = 0; //the two player's choices; r=computer
    String myPick = "Rock"; // the default choice by radio button
    String tool[ ] = {"Rock", "Scissors", "Paper"};
    
    public void init ()
    {
       setBackground (Color.white);
       add (rock);
       add (scissors);
       add (paper);
       go.addActionListener(this);
       add (go);
    }//end init


    public void actionPerformed (ActionEvent evt)
    {
       myPick = choice.getCurrent ().getLabel ();
       repaint ();
    }// end actionPerformed


    public void paint (Graphics g)
    {
       g.setFont (f);
       g.setColor (Color.black);
       r = (int) (Math.random () * 3);
       s = convert (myPick);
       g.drawString ("You picked " + myPick, 30, 100);
       g.drawString ("the Computer picked " + tool [r], 30, 130);
       if (winner (s, r))
           g.drawString ("Congratulations, you won!!", 30, 160);
       else if (winner (r, s))
           g.drawString ("Sorry, the computer won!!", 30, 160);
       else
           g.drawString ("That makes it a tie", 30, 160);
    }// end paint



    public boolean winner (int me, int you)
    {
       if (me == 0 && you == 1)
           return true;
       if (me == 1 && you == 2)
           return true;
       if (me == 2 && you == 0)
           return true;
       return false;
    }//end winner


    public int convert (String name)
    {
       for (int i = 0 ; i < 3 ; i++)
           if (name == tool [i])
       	return i;
       return -1;
    }// end convert

} // Ass3s4p28 class




Sponsored by ECOO and SIG-Computer Science

.