CSci 2101 Lab 2. Java loops and randomness.

Due Monday, January 27th, at 11:59pm (by e-mail)

24 points

Reminder of the setup:

Lab tasks

Make sure that you test for different conditions.

Problem 1 (6 points)

Write a loop that counts the number of times a character appears in a string. For instance, 'r' appears in the string "Morris" 2 times. In the beginning of main create variables for the string and the character:

String str = "Morris";
char c = 'r';
You can test your program by changing the string and the character. Comment out your previous tests, don't delete them.
Hint: declare and initialize (to zero) a variable count before the loop, add 1 to the variable every time you encounter the character you are checking for. Print out the counter variable after the loop. Make sure your printing clearly states what you are printing.

Problem 2 (10 points)

Write a loop that, given a positive integer number, prints out all of its pairs of factors. For instance, when the number is 12, the program should print:

12 can be factored as:
1 and 12
2 and 6
3 and 4
If the number is a perfect square, it's ok to print its root twice:

16 can be factored as:
1 and 16
2 and 8
4 and 4
However, make sure thatt every pair is printed only once. A function that gives you a square root of a number is Math.sqrt. You can use it as Math.sqrt(16) (which results in 4). Check what it returns for numbers that aren't perfect squares.
Change the number several times to test your loop. As before, comment out old tests, don't delete them.

Problem 3 (8 points)

Write a loop that generates random numbers in the range between 1 and 6 (inclusive) until they add up to 20 or higher. In the loop print all the numbers that you have generated. Print the sum after the loop.
Hint: use a while loop, not a for loop, since you don't know ahead of time how many times the loop needs to run.

How to submit

Send the java file(s) by email to me: elenam at The subject of the message must be 2101 Lab 2. Make sure to CC your group partner if you worked with another person.

CSci 2101 course web site.

The views and opinions expressed in this page are strictly those of the page author. The contents of this page have not been reviewed or approved by the University of Minnesota.