15-110 Introduction to Programming [Reid-Miller]


LAB eXtra [while and do loops]

Objective

Exercises

Using Eclipse, write a simple Java program in a project named LabX that contains a class named LoopTester with a main method.

For each of the following exercises, do not move on to the next exercise until you have the current exercise working correctly.

  1. In the main method write the java code corresponding to the flowchart below. Before the loop assign n to 20. After the loop print the values of sum1, sum2, and sum3. In a comment, explain what the loop is computing and the relationship amoung sum1, sum2, and sum2.

    In part 2 you will write a method that returns a random integer between x and y. In parts 3-5 your main method will call this method supplying different values for x and y.
  2. Next, write a static method to compute and return a random integer between x and y, inclusive, assuming x ≤ y. Your method should not assign values to x or y nor print the random number. Instead it will return the random number. Your static method should have the following header:

    public static int getRandomNumber(int x, int y) 
    

  3. After the first loop in the main method print out 20 random integers between 5 and 10 (inclusive) on the same line with one space in between each number:

  4. After your second loop, write another loop that prints out random integers between 10 and 100 (inclusive) on the same line, each separated with a single space, until it prints out the first random number greater than 90. Use your static method again.

Advanced Exercise (If you have time...)

  1. After your third loop, write another while loop that prints out random integers between 100 and 999 (inclusive). until it has printed out five even numbers. The five even numbers do not have to be one after another. We're only looking for a total of five even numbers.

  2. Add a fifth while loop that prints out random integers between 1000 and 9999 (inclusive), one per line, until at least one of the following occurs: