/******************************* * Playing with analyzing coin tosses. * * The bug from version 1.0 is fixed. * * Challenge: modify this program to count toss 20 coins many * times, and count how many of those have 1 head, 2 heads, ... * (Leave out all the the detailed 1:head printing I have below.) * These numbers will form what's called a "Bell curve." * And for a *really* good time, graph the resulting bell curve * with spaces and * chars, on its side so it looks something like * 1 * * 2 * * 3 * * ... etc. * where the number of spaces before the "*" depends on how many * times that number of heads turned up. * * @author Jim mahoney * @version 1.1, Oct 7, 10pm * ****/classCoinFlipping{publicstaticvoidmain(String[]args){inthowMany = 20;intcounter = 1;doubleheadCount = 0; print(" Tossing a coin " + howMany + " times.");while(counter<=howMany){booleanisHead = coinToss();if(isHead){headCount++;}print(" " + counter + ": " + booleanToString(isHead)+ "."); counter++;}print(" Total number of heads = " + headCount + "."); // Debugging - why are we getting average = 0 ? System.out.println(" headCount = " + headCount); System.out.println(" howMany = " + howMany); print(" Average number = " + headCount/howMany + ".");}// convert a boolean (true or false) to a String ("heads" or "tails")publicstaticString booleanToString(booleanx){if(x){return"heads";}else{return"tails";}}publicstaticbooleancoinToss(){// Can you find the Math.random documentation in the Java API ? // How about trying the "ask Google" method?doublerandomNumber = Math.random(); // between 0 and 1if(randomNumber>0.5){returntrue;}else{returnfalse;}}// Print a line of dashes, i.e. " - - - - - - - - - "publicstaticvoidline(){intiDashCount=20; System.out.print(">");while(iDashCount>0){System.out.print(" -"); iDashCount--;}System.out.println(" ");}// I get tired of typing "System.out.println". // So this lets me just type "print".publicstaticvoidprint(String s){System.out.println("> "+s);}}

syntax highlighted by Code2HTML, v. 0.9.1