The Computer Finally Listens!

← Back to assignments

Logic & Computation · Fundamentals laboratory

Your next Java lab

Practice variables and decisions, then teach your program to read keyboard input and generate random numbers. Work through the ten problems in order, one small success at a time.

10 problems · Variables & conditionals · Scanner & Random

Before you begin

  1. Create a file named FundamentalsLab.java using the starter below. Fill in your name and date.
  2. Write your solutions inside main, beneath the matching problem labels. Keep the imports, setup lines, and closing braces.
  3. Complete one problem, run it, and try its checks before moving on. Use different variable names for each problem.
  4. For input problems, print a prompt before reading the answer. Type the answer in the terminal and press Enter.
  5. All text answers in this lab are one word. Assume users enter the requested type of input. You do not need to handle invalid entries.
  6. Each problem runs once. To try another input or random result, run the program again manually. Do not use for or while loops.

Your answers must come from your variables. Example runs show what a program might print; your code must work with other inputs too. When you test a later problem, the program will still run the earlier problems first.

Quick reference

Two new tools, familiar ideas

1. Let Scanner read an answer

Scanner reads what you type. The starter creates one scanner named keyboard; reuse it for every input problem. Ask a question, read the answer into a variable, and then use that variable.

System.out.println("Enter a whole number:");
int number = keyboard.nextInt();
System.out.println("You entered: " + number);
Choose a reading method that matches your variable
InputExample
A whole numberint count = keyboard.nextInt();
A decimal numberdouble price = keyboard.nextDouble();
One wordString word = keyboard.next();

When the program waits after a prompt, it is waiting for your answer. Click the terminal, type the value, and press Enter. Use next() for this lab’s one-word text answers.

2. Let Random choose a number

The starter creates a Random object named random. The bound in nextInt(bound) is excluded: random.nextInt(6) can produce 0, 1, 2, 3, 4, or 5.

Random integer expressions used in this lab
ExpressionPossible values
random.nextInt(2)0 or 1
random.nextInt(6) + 11 through 6, inclusive
random.nextInt(10) + 11 through 10, inclusive

Generate once, store, then use. Each call asks for another random result, which may repeat a previous result. Store a number before you print or compare it.

3. Remember your comparisons

CodeMeaning
=Assign a value to a variable.
==Compare two numeric values for equality.
>, <Greater than; less than.
>=, <=Greater than or equal to; less than or equal to.
word.equals("hello")Compare String contents. Capitalization matters.
number % 2Find the remainder after dividing by 2.

An if / else if / else chain selects one branch. Java checks conditions in order; the final else handles what remains. Keep braces around each branch and do not put a semicolon after if (...).

Java reference: Scanner · Random

Starter code

Copy this into FundamentalsLab.java. The filename must match public class FundamentalsLab. Replace each TODO comment with your solution; add lines as needed.

/*
 * Name:
 * Project: The Computer Finally Listens!
 * Date:
 */
import java.util.Scanner;
import java.util.Random;

public class FundamentalsLab {
    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
        Random random = new Random();

        // START: Write your solutions below this line.
        // Use different variable names for each problem.

        System.out.println("Problem 1");
        // TODO: The Computer Would Like to Meet You

        System.out.println("Problem 2");
        // TODO: The Suspiciously Affordable Snack Shop

        System.out.println("Problem 3");
        // TODO: You Must Be This Tall to Ride the Shopping Cart

        System.out.println("Problem 4");
        // TODO: Even Steven or Odd Todd?

        System.out.println("Problem 5");
        // TODO: The Number’s Entire Personality

        System.out.println("Problem 6");
        // TODO: The World’s Least Secure Secret Club

        System.out.println("Problem 7");
        // TODO: A Die That Cannot Fall Under the Desk

        System.out.println("Problem 8");
        // TODO: The Coin Has Spoken

        System.out.println("Problem 9");
        // TODO: You Versus the Computer: Dice of Destiny

        System.out.println("Problem 10");
        // TODO: The Computer Gives You Homework

        // END: Keep this line after all of your solutions.
        keyboard.close();
    }
}

Keep keyboard.close(); at the end. Put every solution above it. The starter supplies the only Scanner and Random objects you need.

The 10 problems · Part 1

Ask, store, and decide

Problems 1–6 use Scanner to practice your fundamentals.

Scanner · String · output

1. The Computer Would Like to Meet You

Ask the user to enter their first name. Store their answer in a String variable, then print a greeting containing that variable.

Example run

Enter your first name:
Sofia
Hello, Sofia! Welcome to the laboratory.

Hint: Use keyboard.next() to read the name. Use + to connect your message to the variable.

Check: Run the program with a different name. The greeting should change without editing your code.

Scanner · double · arithmetic

2. The Suspiciously Affordable Snack Shop

Ask the user for the price of a snack and the price of a drink. Store both prices in double variables. Calculate their sum, store it in another variable, and print the total.

Assume both prices are zero or greater. There is no tax.

Example run

Enter the snack price:
2.50
Enter the drink price:
1.25
Your total is: 3.75

Hint: Read each price with keyboard.nextDouble(). Enter numbers without a dollar sign.

Check: Prices of 4.0 and 2.0 should produce 6.0. You do not need to format the answer to two decimal places.

Scanner · int · if / else

3. You Must Be This Tall to Ride the Shopping Cart

Ask the user for their height in whole centimeters. A rider must be at least 140 centimeters tall.

Use if and else to print exactly one message:

Example run

Enter your height in centimeters:
145
You may ride the shopping cart.

Hint: Read the height with keyboard.nextInt(). “At least” includes the boundary number.

Check: Test 139, 140, and 141. The last two should both allow the rider.

Scanner · remainder · if / else

4. Even Steven or Odd Todd?

Ask the user to enter a whole number. Store it in an int variable. Print whether the number is even or odd.

Example run

Enter a whole number:
17
That number is odd.

Hint: The remainder operator is %. An even number has a remainder of 0 when divided by 2.

Check: Test 8, 7, and 0. Zero should be identified as even.

Scanner · comparisons · three branches

5. The Number’s Entire Personality

Ask the user to enter an integer. Use an if / else if / else chain to identify it as positive, negative, or zero.

Print exactly one of these messages:

Example run

Enter an integer:
-4
That number is negative.

Hint: First check whether the number is greater than zero. Next check whether it is less than zero. What possibility remains?

Check: Test 12, -12, and 0. Each run should print only one result.

Scanner · String · .equals()

6. The World’s Least Secure Secret Club

Ask the user to enter a password. Store it in a String variable. The password is penguin, written entirely in lowercase.

If the password matches, print Welcome to the secret club. Otherwise, print The penguins do not recognize you.

Example run

Enter the password:
penguin
Welcome to the secret club.

Hint: Compare text using .equals(...). For example, word.equals("hello") checks whether word contains "hello". Your condition should use your password variable and the club’s actual password.

Check: Test penguin, Penguin, and potato. Only the first should be accepted.

Part 2

Let chance choose

Problems 7–9 introduce Random and reuse familiar decisions.

Random · int · output

7. A Die That Cannot Fall Under the Desk

Generate one random integer from 1 through 6, store it in an int variable, and print the result. This problem does not require keyboard input or a conditional.

Use this expression:

random.nextInt(6) + 1

nextInt(6) produces an integer from 0 through 5; adding 1 shifts that range to 1 through 6.

Possible output / run

You rolled: 4

Hint: Save the generated number in a variable, then print that variable. The example is one possible result.

Check: Run the program several times manually. Every result must be between 1 and 6. Repeated results are normal.

Random · equality · if / else

8. The Coin Has Spoken

Generate one random integer using random.nextInt(2). This produces either 0 or 1. Store the result in a variable, then use if and else:

Possible output / run

Heads!

Hint: Generate the number once, then check the stored value.

Check: To check both branches, temporarily replace the random expression with 0, then with 1. Restore the random expression afterward.

Random · comparisons · three branches

9. You Versus the Computer: Dice of Destiny

Generate two random integers from 1 through 6. Store one as the player’s roll and the other as the computer’s roll.

Print both values. Then use an if / else if / else chain to announce:

Possible output / run

Your roll: 5
Computer's roll: 2
You win!

Hint: Use the same expression as Problem 7 for each roll. Compare the stored rolls after printing them.

Check: Temporarily use fixed player/computer rolls of 6 and 2, then 2 and 6, then 3 and 3. Restore both random expressions afterward.

Part 3

Bring both tools together

Use input, random numbers, arithmetic, and one decision.

Scanner + Random · arithmetic · decisions

10. The Computer Gives You Homework

Generate two random integers from 1 through 10. Store each number in its own variable.

  1. Display an addition question using those numbers.
  2. Ask the user to type an answer and store it in an int variable.
  3. Calculate the correct answer using your two stored numbers.
  4. If the user is correct, print Correct! The computer is impressed. Otherwise, print the correct answer.

Possible output / run

What is 4 + 7?
10
Not quite! The correct answer is 11.

Hint: Use random.nextInt(10) + 1 for each number. Generate the numbers once and reuse them when displaying the question and calculating its answer.

Check: Try one correct answer and one incorrect answer. Each run asks only one question.

Before submitting

Submit your completed FundamentalsLab.java file to [email protected].