Recursion, Graphics, Random and While Quiz: review exercises:
Tracing: what will these print:
1. what prints when I call whileRoller(25)?
public static void whileRoller(int numberToRoll)
{
int myPlace = 1;
int roll = 4;
System.out.println("I
just rolled a " + roll);
while (myPlace + roll
<=numberToRoll)
{
myPlace = myPlace + roll;
System.out.println("I am now in place " + myPlace);
roll = 10;
System.out.println("I just rolled a " + roll);
}
if( myPlace ==
numberToRoll)
{
System.out.println("I
won");
}
else
{
System.out.println("I
lost");
}
}
2. What is returned by the call countby3(8)?
public static int countby3(int x)
{
if (x <= 0)
{
return 0;
}
else
{ int y = countby3(x-3);
System.out.println(x);
return x + y;}
}
3. Draw what will be added to the canvas when I call
printSomething(500,500).
public static void printSomething (int x, int y)
{
WorldImage shape1 = AImage.makeCircle(x/10,Color.blue,
Mode.filled);
WorldImage shape2 = AImage.makeRectangle(x/10,y/5,Color.red,
Mode.filled);
WorldImage shape3 = AImage.makeRectangle(x,y,Color.yellow,
Mode.filled);
shape3 = shape3.place(shape1,x/2,y/5);
shape3 = shape3.place(shape2,x/2,y/5*2);
shape3.show();
}
Coding Exercises:
1. Recursion: (from book) Write a method called writeNums that
takes an integer as a parameter and prints that many integers
starting with 1 in sequential order, separated by commas. See
sample runs:
writeNums(5);
produces 1, 2, 3, 4, 5
writeNums(10)
produces 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
2. While & Random: Write a program that keeps asking a user if
they want to roll the dice. It stops when the user says no. As it
rolls the dice, it prints the dice throw. It prints a total of all
the dice when the user is done throwing dice. See sample run:
Do you want to throw the dice?
yes
you threw a 5
do you want to throw again?
yes
you threw a 6
do you want to throw again?
yes
you threw a 3
do you want to throw again?
no
the total of your throws is 14
3. Make a method called matcher that takes in two doubles and
returns true if the two variables are equal to each other. It is
considered equal if the absolute difference between the two
variables is less than .001.
some tests you can run;
matcher(5.,6.) should be false
matcher(6.,5.) should be false
matcher(5.,5.) should be true
matcher(5.0001,5.) should be true
matcher(5.01,5.) should be false
4. Graphics & while
Draw a row of boxes, stopping when the x value is .9
(Make your boxes RectangleSprites of length .09 and width .09 and
then move over .1 x every time.)