Time estimate: not long, an hour or so should suffice.
Due: By classtime Thur, 10/5. (If you've more pressing work and desire an extension, send me a request via e-mail.)
Collusion: You may work together on the lab; but for the ensuing homework you each should maintain and submit your own program. If you wish to share the results of your lab before starting on the homework, simply email the file to the partner whose account you are not in. S/he can retrieve it from the mail.
What's emphasized in this lab:
2. Modify this code so it uses a while rather than the do-while loop:
int i = 0; System.out.println(); //What's this statement do? do { double x = Math.random(); System.out.println(i+" "+x); i++; } while(i<10);
for(int i=0; i<10; i++) { double x = Math.random(); System.out.println(i+" "+x); }Notice carefully the syntax of the for-statement; note how compact it is. The int i can be declared right in the loop rather than before it.
Try to output the value of i after the loop. What happens?
Note when the autoincrementation occurs. Is it at the beginning or the end of the loop?
When is the condition, i<10, tested - at the beginning or end?
public static int ranInt( int a, int b) { return (int) (a+(what goes here?)*Math.random()); }You would call this in main by using the actual arguments, e.g.
int pips = ranInt(1,6)
int counter1 = 0, counter2 = 0,...,counter6 = 0;Now in the loop where pips is generated, let's increment the appropriate counter, which is counter1 for 1 pip, etc, each time pips is generated.
for(int i=0; i<60; i++) { int pips = ranInt(1,6); if (pips == 1) counter1++; if (pips == 2) counter2++; ... if (pips == 6) counter6++; }
Note that there's no output in the loop. Rather, after the loop let's output the counters...
System.out.println("There were:"); System.out.println(counter1 + "1's"); System.out.println(counter2 + "2's"); ... System.out.println(counter6 + "3's");Run the program. Check that the counters add up to 60.
for(int i=0;i<60;i++) { int pips = ranInt(1,6); switch(pips) { case 1: counter1++; //break; case 2: counter2++; //break; case 3: counter3++; //break; case 4: counter4++; //break; case 5: counter5++; //break; case 6: counter6++; } }Test it. Notice this has almost the same effect. However, now were getting the cumulative counts. Uncomment the breaks and it should come out right. Once you're use to it, I think switch is easier to read then if-else's and logically better than if's. Switch just picks out the right case and increments that counter.
The purpose of the RanTest or TestRan class is simply to test the Ran class.
This is the end of the lab.
Strictly Speaking. In Java, a non-instantiable class, i.e. one with only class variables and class methods can actually be instantiated. But, in my opinion, that's not good style. Thus, one could have
Ran r = Ran(); int pips = r.ranInt(1,6);but simply
int pips = Ran.ranInt(1,6);is preferable. More on style to come.