Author Topic: COIN FLIPPING - Using functions for subtasks  (Read 4193 times)

louiecerv

  • Moderator
  • User
  • *****
  • Posts: 85
COIN FLIPPING - Using functions for subtasks
« on: January 22, 2006, 11:52:49 PM »
Code: [Select]


import java.util.Scanner;

class CoinFlipping
{

private static char ThrowCoin()
{
   if ( Math.random() > 0.5 )
       return 'H';
   else
       return 'T';
}

public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
       

System.out.println("** COIN FLIPPING SIMULATION **");
do {

System.out.print("Number of tosses (even): ");
int N = keyboard.nextInt();
System.out.print("Number of repetitions: ");
int R = keyboard.nextInt();
System.out.println("");

String format = "%1$-" + (N+4) + "s%2$-4d%3$-4d%4$-8s\n";

//counts the number of times heads and tails are equal
int h_equals_t=0;

       for (int i = 0; i<R; i++)
       {      
           int heads=0, tails = 0;
           String output = "";
           for (int j = 0; j<N;j++)
           {
               char result = ThrowCoin();
               if (result=='H')
                   heads++;
               else
                   tails++;
               output += result;    
           }
           
String status="";            

           if (heads == tails)
           {
               h_equals_t++;
               status = "equal";
           } else
           {
            status = "";
           }  
           
           System.out.format(format, output, heads, tails, status);

       }
        System.out.println("Heads=Tails " + h_equals_t +
              " out of " + R + " times.\n");
             
} while (1==1);        
}
}

Analyze. Design. Develop. Debug. Deploy. Maintain.

louiecerv

  • Moderator
  • User
  • *****
  • Posts: 85
not OOP design yet
« Reply #1 on: January 23, 2006, 12:15:51 AM »
I hope we could have a good discussion of this sample code as introduction to OOP.  This sample was chosen to show to create functions for subtasks.  Java is a pure OOP language yet beginners may choose to be procedural oriented while not yet comfortable with OOP design.

The paradigm shift can be disorienting to most.  Those who start learning to program using Java as first language find it so much easier to understand programming using objects.  For most of us migrating from C/C++, the challenge is how to discard the old habits of function-oriented programming.
Analyze. Design. Develop. Debug. Deploy. Maintain.