Logic & Computation · Loops laboratory
One instruction. Many repetitions.
You have taught your programs to read, calculate, and make decisions. Now teach them to repeat. Work through ten small problems using familiar variables, conditionals, Scanner, and Random.
Before you begin
- Create
LoopsLab.javafrom the starter below. Fill in your name and date. - Write each solution inside
main, below its matching problem label. Complete one problem, run it, and try its checks before moving on. - Use the loop type requested by each problem. Problems 1–6 use
for; Problems 7–9 usewhile; Problem 10 brings the tools together withfor. - Reuse the supplied
keyboardandrandomobjects. Keepkeyboard.close();after all solutions. - Use different names for variables declared directly inside
mainin different problems. A counter declared inside aforheader belongs to that loop. - Assume users enter the requested data type. Only Problems 8 and 9 require repeated prompting until an answer is accepted.
- Use one loop at a time. You do not need nested loops, arrays,
break, orcontinue.
Remember: When you run the whole program, it will run earlier problems before the one you are testing. Type each requested answer in the terminal and press Enter. Example runs include the user’s typed responses; your code does not print those responses for them.
Part 1 notes · Read before Problems 1–6
Meet the for loop
A loop repeats a block of code. A for loop is convenient when you know how many repetitions you want, or which numbers you want to visit.
Read this example before beginning. Predict what it prints, then trace the changing value of round.
for (int round = 1; round <= 3; round++)
{
System.out.println("Practice round " + round);
}
| Part | What it does |
|---|---|
int round = 1 | Start the counter at 1. This happens once. |
round <= 3 | Check the condition before each repetition. If it is false, leave the loop. |
round++ | Add one after the body finishes, then check the condition again. |
The body prints rounds 1, 2, and 3. After the third repetition, the update makes round equal to 4. The condition is false, so there is no fourth repetition.
Keep track of what changes
| Code | Meaning |
|---|---|
count++; | Add one to count. This is the same as count = count + 1;. |
count--; | Subtract one from count. |
total = total + amount; | Add amount to the old total and store the new total. |
number % 2 == 0 | Check whether a number is even. |
Where does this line belong?: Initialize a running total or score before the loop, change it inside the loop, and print the finished result after the loop. A variable created inside the loop’s braces cannot be used outside those braces.
Braces and semicolons: Keep braces around the loop body and use Allman (ANSI) style, as shown above: the opening brace goes on the next line, and the closing brace lines up with it. The two semicolons belong inside a for header. Do not put a semicolon between the closing ) and the opening {.
Your familiar tools
| Expression | Use |
|---|---|
keyboard.nextInt() | Read an integer. |
keyboard.next() | Read one word. |
random.nextInt(6) + 1 | Generate an integer from 1 through 6. |
random.nextInt(10) + 1 | Generate an integer from 1 through 10. |
Need a refresher? Revisit the fundamentals lab’s Java cheat sheet.
Starter code
Copy this into LoopsLab.java. The filename must match public class LoopsLab. Replace each TODO comment with your solution; add lines as needed.
/*
* Name:
* Project: The Computer Learns to Repeat!
* Date:
*/
import java.util.Scanner;
import java.util.Random;
public class LoopsLab
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
Random random = new Random();
// START: Write each solution below its problem label.
System.out.println("Problem 1");
// TODO: The Computer Has Been Told Once
System.out.println("Problem 2");
// TODO: Counting Without Copy and Paste
System.out.println("Problem 3");
// TODO: You Decide When We Stop Counting
System.out.println("Problem 4");
// TODO: Even Steven and Odd Todd Take Attendance
System.out.println("Problem 5");
// TODO: The Computer Keeps a Running Total
System.out.println("Problem 6");
// TODO: A Die That Finally Rolls More Than Once
System.out.println("Problem 7");
// TODO: The Extremely Small Rocket Launch
System.out.println("Problem 8");
// TODO: The Computer Politely Insists
System.out.println("Problem 9");
// TODO: The Penguins Give You Another Chance
System.out.println("Problem 10");
// TODO: The Computer Gives You Three Homework Questions
// END: Keep this line after all of your solutions.
keyboard.close();
}
}Keep the setup: The starter supplies the only Scanner and Random objects you need. Keep all your solutions above keyboard.close();.
Problems 1–6
Repeat a known number of times
Begin with small for loops, then reuse your familiar decisions, input, and random numbers.
1. The Computer Has Been Told Once
Use a for loop to print the sentence below exactly five times, with each repetition on its own line. Write the printing statement only once in your code. This problem does not need keyboard input.
Example output / run
I will save my Java file before running it.
I will save my Java file before running it.
I will save my Java file before running it.
I will save my Java file before running it.
I will save my Java file before running it.
Hint: Use a counter that starts at 1, continues through 5, and increases by one each time.
Check: Count the output lines. There should be five copies of the sentence, not four or six.
2. Counting Without Copy and Paste
Use a for loop to print the integers 1 through 10, inclusive, one per line. Your printing statement must use the loop’s counter variable. Write the printing statement only once.
Example output / run
1
2
3
4
5
6
7
8
9
10
Hint: In Problem 1 the message stayed the same. Here, print the variable that changes after each repetition.
Check: The first number should be 1, the last should be 10, and there should be ten numbers.
3. You Decide When We Stop Counting
Ask the user for an integer from 1 through 20. Store it, then use a for loop to print every integer from 1 through that number, inclusive.
Assume the input is in the requested range. You do not need a validation loop for this problem.
Example output / run
Enter a number from 1 through 20:
4
1
2
3
4
Hint: Read the endpoint once, before the loop, using keyboard.nextInt(). Use that stored value in the loop condition.
Check: Input 1 should print only 1. Input 4 should print four numbers. Input 20 should end at 20.
4. Even Steven and Odd Todd Take Attendance
Use a for loop to visit the integers 1 through 10. Inside the loop, use if / else to label each number as even or odd.
Print the number and its label together on one line. This problem does not need keyboard input.
Example output / run
1 is odd.
2 is even.
3 is odd.
4 is even.
5 is odd.
6 is even.
7 is odd.
8 is even.
9 is odd.
10 is even.
Hint: Reuse the % 2 test from the fundamentals lab. This time, test the loop counter. A remainder of 0 means the number is even.
Check: There should be ten labeled numbers: five even and five odd. The last line should be 10 is even.
5. The Computer Keeps a Running Total
Ask the user for an integer from 1 through 20. Use a for loop to add all integers from 1 through that number. Print the total after the loop finishes.
Assume the input is in the requested range. Use repeated addition in your loop rather than a sum formula. For input 4, the total is 1 + 2 + 3 + 4 = 10.
Example output / run
Enter a number from 1 through 20:
4
The total is 10.
Hint: Create an int total with the starting value 0 before the loop. Each repetition adds the current counter to the total. Do not reset the total inside the loop.
Check: Input 1 gives 1; input 5 gives 15; input 20 gives 210. Print the completed total once.
6. A Die That Finally Rolls More Than Once
Use a for loop to roll a six-sided die five times. On each repetition, generate a new value using random.nextInt(6) + 1, store it, and print it with the roll number.
This problem does not need keyboard input. Repeated results are normal.
One possible output
Roll 1: 4
Roll 2: 2
Roll 3: 2
Roll 4: 6
Roll 5: 1
Hint: Put the random-number generation inside the loop. Generating once before the loop and reusing that value would print the same stored roll five times.
Check: There should be five rolls labeled 1 through 5. Every die value must be between 1 and 6. Your results do not need to match the example.
Part 2 notes · Read before Problems 7–9
Meet the while loop
A while loop checks a condition before each repetition. It is useful when you want to keep going until something changes, such as a user finally entering an acceptable answer. It can also count, as in this example:
int round = 1;
while (round <= 3)
{
System.out.println("Practice round " + round);
round++;
}
This prints the same three practice rounds as the earlier for example. Here, the counter starts before the loop, and the update is written inside the body.
- Set up the value the condition will check.
- Check the condition. If it is false, skip the body and continue after the loop.
- If it is true, run the body. Change the counter or read a new input so the condition can eventually become false.
- Return to the condition and check again.
A loop can run zero times: If the first input is already acceptable, a retry loop should skip its body. There is no need to print an error or ask again.
Avoid an endless loop: If the value in the condition never changes, the loop may never stop. For a countdown, update the counter inside the loop. For a retry prompt, read the replacement answer inside the loop. If your program runs endlessly in the terminal, press Ctrl+C, then check the condition and update.
When you compare text
Use .equals() for String contents. The operator ! means “not.” For example, !word.equals("hello") is true when word is not "hello". Capitalization matters.
Before each problem, ask yourself: What repeats? What changes? What makes this loop stop?
Problems 7–9
Keep going while a condition is true
Practice a countdown, then teach your program to ask again when an answer is not accepted.
7. The Extremely Small Rocket Launch
Create an integer variable with the value 5. Use a while loop to print a countdown from 5 through 1, one number per line. After the loop, print Blast off!
This problem does not need keyboard input.
Example output / run
5
4
3
2
1
Blast off!
Hint: Decrease the countdown variable by one inside the loop. The condition should let the loop run while the number is greater than zero.
Check: Do not print 0. Print Blast off! exactly once, after the countdown. Be ready to explain why the loop stops.
8. The Computer Politely Insists
Ask the user to enter a positive integer. If they enter 0 or a negative integer, use a while loop to print an error message and ask again. Continue until the value is greater than zero.
After the loop, print the accepted number. Assume every entry is an integer; you do not need to handle letters or decimal entries.
Example output / run
Enter a positive integer:
0
That number must be greater than zero. Try again:
-3
That number must be greater than zero. Try again:
4
Accepted: 4
Hint: Read the first number before the loop. While it is invalid, print the retry prompt and read a replacement into the same variable. An unchanged invalid value would keep the loop running.
Check: Test 0, then -3, then 4 in one run. In a separate run, enter 4 first: accept it immediately without printing an error.
9. The Penguins Give You Another Chance
The secret-club password is still penguin, entirely in lowercase. Ask the user to enter a password, then use a while loop to keep asking until it is correct.
Print a rejection message and another prompt after each incorrect entry. After the loop, print Welcome to the secret club. once. All passwords are one word; there is no attempt limit.
Example output / run
Enter the password:
potato
The penguins do not recognize you. Try again:
Penguin
The penguins do not recognize you. Try again:
penguin
Welcome to the secret club.
Hint: Use keyboard.next() and .equals(). The operator ! means “not”: !password.equals("penguin") is true while the password is incorrect. Read a new password inside the loop.
Check: Test the correct password immediately, then test two incorrect entries followed by the correct one. Penguin is not accepted. The welcome message appears once.
Problem 10
Bring it all together
Finish the quarter with a short quiz built from the tools you have practiced.
10. The Computer Gives You Three Homework Questions
Turn the fundamentals lab’s addition question into a three-question quiz using a for loop.
- Generate two new random integers from 1 through 10 on each repetition.
- Display their addition question, including the question number.
- Read the user’s integer answer.
- Print whether it is correct. If it is wrong, show the correct answer.
- Add one to the score only when the answer is correct.
After all three questions, print the final score out of 3. Each question gets one answer; do not keep asking until the answer is correct. Repeated random questions are allowed.
One possible run
Question 1: What is 4 + 7?
11
Correct!
Question 2: What is 2 + 5?
6
Not quite! The correct answer is 7.
Question 3: What is 9 + 1?
10
Correct!
You answered 2 out of 3 correctly.
Hint: Set the score to zero before the loop. Generate and store both numbers inside the loop using random.nextInt(10) + 1. Reuse those stored numbers for the question and its answer. Print the final score after the loop.
Check: Try three correct answers for a score of 3, three deliberately incorrect answers for 0, and a mixed run. The program must ask exactly three questions.
Before submitting
- Fill in your name and date at the top of
LoopsLab.java. - Complete all ten problems using the requested loop types. Keep each problem’s output clearly labeled.
- Try every problem’s checks. Confirm that fixed loops run the correct number of times.
- For Problems 8 and 9, test both an immediately accepted answer and incorrect answers followed by a correct one.
- Keep totals and scores outside their loops so they are not reset on every repetition.
- Make sure random values are generated where the directions request them. Restore random expressions if you temporarily used fixed values for testing.
- Be ready to explain one
forloop and onewhileloop: what repeats, what changes, and why it stops.
Submit your completed LoopsLab.java file to [email protected].