CSERD


  • userhome
  • catalog
  • resources
  • help

Programming in Java


Shodor > CSERD > Resources > Tutorials > Programming in Java

  Intro  •   Lesson 1  •   Lesson 2  •   Lesson 3  •   Lesson 4  •   Lesson 5  •   Final Challenge


Programming in Java - Lesson 4

Functions

You can see that a code which could track a scientifically or mathematically interesting set of probabilities, be it cards in a deck or scattering of photons in the sun, is going to get real complicated real quick.

As programmers, we want to be able to have some sort of shorthand for the operations we perform over and over. In Java, (as in many computer languages) we can program functions, which take some input, do something with it, and return some output. Functions which do not return a value are called voids. (Note, what is the main function type?)

This gets defined as 'datatype name(args) { statements }'

Consider the following update of our gambler program, in which we have a function call whenever we want to roll the dice. The function returns a boolean value, either it is true that the dice roll was successful, or it was not. It takes as an argument the chance of a successful dice roll.

public class TheGambler2 {

    public static void main(String [] args) {

        // Initialize variables;
        double balance=5.0;

        //while bets can still be made, keep gambling.
        while (balance>=0.0) {
            //make a bet, and adjust balance.
            if (rollDice(0.5)) {
               balance += 1.0;
            } else {
               balance -= 1.0;
            }
        }

    }



    //rollDice takes a chance for success, and returns true if a random
    // number comes in under that chance, and false otherwise
    public static boolean rollDice(double successChance) {
        if (Math.random()<successChance) {
            return true;
        } else {
            return false;
        }
    }

}

Compile and run the program. Notice the use of an "else", where one set of commands is run if a statement is true, or ELSE a different set of commands is run if the statement is NOT true.

Exercises

Modify the program to keep track of the maximum balance, and output it at the end of the program.

Add a function which computes a bet based on the current balance, where the gambler bets the lesser of 1 or 10% of the current balance.


©1994-2024 Shodor