Friday, September 6, 2013

JAVA Case Study #2: Divide Items Equally

CASE STUDY #2: Divide Items Equally

Next let's look at this strange code for a program that will divide the total number of gumballs equally among a varied number of children:
import java.util.Scanner;

class EquallyDivide
{

    public static void main(String args[]) {
        Scanner myScanner = new Scanner(System.in);
        int gumballs;
        int kids;
        int gumballsPerKid;

        System.out.print("How many gumballs? ");

        gumballs = myScanner.nextInt();
        System.out.print("How many kids? ");

        kids = myScanner.nextInt();
        gumballsPerKid = gumballs / kids;

        System.out.print("Each kid gets ");
        System.out.print(gumballsPerKid);
        System.out.println(" gumballs.");
    }
}
 
So let's work with this code:
  • Add some comments / labels.
  • What is the difference between:
    •  System.out.println
    •  System.out.print
  • With variable names like "gumballs" or "kids" or "gumballsPerKid", this program is pretty specific.  What sorts of names could we use for variables to make this program usable for other purposes?  The "gumballs" variable might be more useful as "items", for example.  Remember, however, that you can change all instances of "gumballs" but "gumballsPerKid" is a completely different variable name.
  • What code could we add to figure out how many gumballs are left over after they have been divided equally?

No comments:

Post a Comment