← Back to CI401
CI401 Introduction to Programming · University of Brighton · Week 2

Input and Repetition: Scanner + While Loop

Sunday prep. Read this before the lecture and lab. It follows the slides in order. Every new bit of Java is explained, with a closed “Show me the Python version” box you can open if it helps.

Files: lecture slides (.pptx) · lab project scannerWhile.zip

What to do today (about 55 minutes)

  1. 5 min – Read “Input & output” (sections 1 and 2).
  2. 20 min – Read the Scanner sections (3 to 6). Open the Python boxes only if you need them. Tracers 1 and 2 are inside sections 3 and 4.
  3. 20 min – Read the while loop sections (7 to 13). Tracers 3 and 4 are inside sections 9 and 11. The “What will it print?” puzzles are in sections 4, 9 and 11: guess first, then reveal.
  4. 3 min – Read the lab tasks so you know what is coming.
  5. 7 min – Do the 8-question quiz. Aim for 6 or more. Your answers are saved on this computer.

Ticking off. Every section has its own “Mark this section complete” box. Big sections are split into smaller parts, each with a Done box: tick it and that part folds down to one line (tap the line to open it again). Each section ends with a few quick check questions. Get them all right and the section is ticked off and folds away. The bar at the top shows how much you have done. Already know a section? Use “mark done anyway”.

The big idea this week: last week your programs always did the same thing. This week they ask you questions and repeat until you tell them to stop.

1. Input and output (IO)

Programs are not much use if they cannot talk to the outside world. That talk is called input and output, or IO.

Picture it as: Input → [ Program ] → Output.

Why it matters: without input, a program does the same thing every time. With input it becomes interactive.

Humans do IO too. Your senses (sight, hearing, touch, taste, smell) are your input. Talking, facial expressions, moving, writing and singing are your output. In a conversation, one person’s output is the other person’s input.

IO in programs. The simplest program has one input and one output (numbers or text). A program can talk to human users (through devices like the keyboard and screen, which we often just think of as “us”), to other programs, to the internet, or to special hardware such as robots.

2. IO in Java: System.in and System.out

Java gives you two basic channels:

You already used System.out.println(...) last week. Today you use System.in to read what the user types, with Java’s built-in Scanner class.

// Print Hello on the screen, then move to a new line.
System.out.println("Hello");
System.out.println and the dot. Prints the text in the round brackets on the screen and then moves to a new line. The dots join the parts: System (Java’s system tools) → out (the screen) → println (print a line). In general, a dot means “the thing on the right that belongs to the thing on the left”.
Show me the Python version
print("Hello")

Exactly Python’s print. Python also has input() built in for reading the keyboard; Java does not, which is why it needs a Scanner.

3. Scanner example 1: SayHello

The SayHello program

Scanner is a Java class that makes it easy to get input from the user. SayHello asks for your name, then greets you. When you run it, it prints a prompt (a question), then waits. In BlueJ’s terminal there is a line at the bottom where you type. You type Java, press Enter, and it replies.

New word: terminal. The terminal is the text window where the program prints its output and where you type input. In BlueJ it is called the Terminal Window; you type in the bottom part of it.
// Tell Java we want to use the Scanner class.
import java.util.Scanner;

// The class (the box that holds this program).
public class SayHello
{
    // run() holds this program's instructions.
    public void run()
    {
        // Ask the user for their name (the prompt).
        System.out.print("What is your name? ");

        // Make a Scanner called myInput that reads the keyboard.
        Scanner myInput = new Scanner(System.in);

        // Wait for the user to type a word; keep it in name.
        String name = myInput.next();

        // Greet the user by name, then end the line.
        System.out.println("Hello " + name + ", nice to meet you");

        // Close the Scanner: we have finished with it.
        myInput.close();
    }

    // Java starts here: make a SayHello object, call run().
    public static void main(String[] args) {
        new SayHello().run();
    }
}

Every piece of this program, explained:

New word: class (public class SayHello)

New word: class. A class is the container that holds a Java program (or part of one). All Java code lives inside a class. In BlueJ each yellow box is one class. A class can also be a ready-made tool from Java, like Scanner.
public class SayHello. Starts a class called SayHello. public means other code (and BlueJ) is allowed to use it. The class name must match the file name (SayHello.java).
Show me the Python version
class SayHello:
    ...

Python can make classes too, but a small Python program does not need one. Every Java program must sit inside a class.

Curly brackets { }

Curly brackets { }. Mark where the class, a method, a loop or an if starts and ends. Every { needs a matching }.
Show me the Python version
def run():
    print("inside run")   # indented = inside
print("outside run")

Python uses a colon and indentation; Java uses curly brackets and ignores indentation (but indent anyway, for humans).

New word: method (public void run())

New word: method. A method is a named block of instructions, like a Python def. SayHello has two: run() and main(). next() and close() are methods that belong to the Scanner.
public void run() and round brackets. Makes a method called run. void means it does a job but does not hand back an answer. The round brackets ( ) are where a method’s inputs go; run has none. You also use round brackets when you call a method, like myInput.next() or println("Hi").
Show me the Python version
def run():
    print("Hi")

run()

Same as a Python function. Java writes void to say “returns nothing”.

main, where Java starts (and arrays)

public static void main(String[] args). The method Java starts from. In BlueJ you run a class by choosing void main(String[] args). static means it can run before any SayHello object exists. String[] args is an array of Strings we never use. Copy this line as it is.
Show me the Python version
if __name__ == "__main__":
    SayHello().run()

Python runs a file from the top. Java always starts at main, which here just starts run().

New word: array. An array is a fixed-length list of values of one type. String[] args in main is an array of Strings. You do not need it this week.

new

new. new SayHello() makes a new object from the SayHello class; .run() then calls its run method. Likewise new Scanner(System.in) makes a new Scanner object that reads from the keyboard.
Show me the Python version
SayHello().run()

Python makes an object by calling the class name. Java needs new in front.

import

import java.util.Scanner; Tells Java you want to use the Scanner class, which lives in Java’s java.util library. It goes at the very top of the file, above the class.
Show me the Python version
import random          # use a library module
from math import sqrt  # or one thing from it

Same idea as a Python import. Without this line Java says cannot find symbol: class Scanner.

Scanner myInput = new Scanner(System.in);

Scanner myInput = new Scanner(System.in); Makes a new variable called myInput that holds a Scanner, and that Scanner reads its data from System.in (the keyboard). The type Scanner comes first, then the name, then =, then the new object.
Show me the Python version
# Python needs no Scanner:
# input() reads the keyboard directly

Python’s input() is built in. In Java you make a Scanner once, then ask it for input as many times as you like.

next(): reading one word

String name = myInput.next(); Asks the Scanner for the next word the user types and puts it in a new String (text) variable called name. The program waits here until you press Enter.
Show me the Python version
name = input()

Like input(), but next() takes only one word: type New York and you get "New". Java also makes you say the type (String) the first time.

print versus println

print versus println. System.out.print prints and stays on the same line. System.out.println prints and then moves to a new line. The prompt uses print so your answer appears right after the question.
Show me the Python version
print("What is your name? ", end="")  # stay on the line
print("Hello")                       # new line after

Java print = Python print(..., end=""). Java println = a normal Python print. (Python’s input("question") does the prompt and the reading in one go.)

+ to join text

+ to join text. "Hello " + name + ", nice to meet you" joins three Strings into one.
Show me the Python version
print("Hello " + name + ", nice to meet you")

Same as Python.

Semicolon ;

New word: semicolon. The ; at the end of each Java instruction. It means “this instruction ends here”.
Semicolon ;. Every instruction ends with one. Lines that open a block with {, and closing } lines, do not.
Show me the Python version
name = input()   # the end of the line ends it

Python uses the end of the line. Forget the semicolon in Java and BlueJ says ';' expected.

close()

myInput.close(); Closes the Scanner so the system knows you have finished with it. Put it at the end, after you have read everything.
Show me the Python version
# Nothing needed for input() in Python.
# (Files are similar: f.close())

Python’s input() needs no closing.

Variables again, and compiling

Variables again. SayHello uses two variables. myInput holds a Scanner, made with new Scanner(...). name holds a String, filled by asking the Scanner for the user’s answer.

New word: compile. Compiling means Java checks your code and turns it into something the computer can run. In BlueJ you click Compile before you run. If there is a mistake, it will not compile and BlueJ shows an error.

Tracer 1: SayHello (you type Java)

Press Next step. The highlighted line is the one Java is running. Watch the variables and the terminal change. Green lines are comments; Java skips them. In the terminal, what you type appears after the question, and pressing Enter starts a new line.

1// Use the Scanner class.
2import java.util.Scanner;
3
4// The class: the box that holds this program.
5public class SayHello
6{
7 // run() holds this program's instructions.
8 public void run()
9 {
10 // The prompt; print keeps us on this line.
11 System.out.print("What is your name? ");
12 // A Scanner that reads the keyboard.
13 Scanner myInput = new Scanner(System.in);
14 // Wait for one word; keep it in name.
15 String name = myInput.next();
16 // Greet, then end the line.
17 System.out.println("Hello " + name + ", nice to meet you");
18 // Finished with the Scanner.
19 myInput.close();
20 }
21
22 // Java starts here and calls run().
23 public static void main(String[] args) {
24 new SayHello().run();
25 }
26}
Variables
Terminal (what you see)

4. Scanner example 2: TripAdvisor (with a switch)

The TripAdvisor program

Last week StarRating used ratings that were fixed in an array (“hard-coded”). TripAdvisor asks the user instead: where did you go, and how many stars? Then it prints the place and its stars using a switch where each case falls through (no break), so the right number of stars comes out.

// Ask for the place (prompt stays on the same line).
System.out.print("Where have you just visited? ");
// Make the Scanner.
Scanner myInput = new Scanner(System.in);
// Read one word: the place.
String place = myInput.next();
// Ask for the stars.
System.out.print("How many stars would you give it (1-5)? ");
// Read one word: the rating, kept as TEXT, e.g. "3".
String starNumber = myInput.next();
// Show the place and the rating, same line.
System.out.print(place + " (" + starNumber + " stars): ");

// Switch with fall-through: Java jumps to the case that
// matches starNumber and then runs every case below it,
// because there is no break. "3" prints 3 stars.
// Anything else (like "7") jumps straight to default,
// which just ends the line.
switch (starNumber) {
    case "5": System.out.print("*");
    case "4": System.out.print("*");
    case "3": System.out.print("*");
    case "2": System.out.print("*");
    case "1": System.out.print("*");
    default:
        // No more stars to print: just end the line.
        System.out.println("");
}

// Close the Scanner.
myInput.close();

switch, case and default

switch, case and default. switch (starNumber) looks at the value of starNumber and jumps to the case with the same value. Each case label ends with a colon :. default: is the “anything else” case, like a final else.
Show me the Python version
match starNumber:          # Python 3.10+
    case "3":
        print("***", end="")
    case _:                # like default
        pass

Python’s match never runs into the next case. A Java case does, unless you stop it with break.

break, and falling through

break (and why it is missing here). break; means “stop and leave the switch”. Without it, Java falls through and runs the lines of every case below. TripAdvisor leaves out break on purpose: "3" jumps in at case 3 and falls through cases 2, 1 and default, printing three stars.
Show me the Python version
# The nearest Python version of the fall-through trick:
if starNumber in ["1", "2", "3", "4", "5"]:
    print("*" * int(starNumber), end="")
print("")

In most switches you want a break at the end of every case. Here, falling through is the trick that counts the stars.

The cases have quotes ("3") because next() always gives you text, not a number. Combining Scanner with a switch lets the user control what the program does, instead of fixed data. Tracer 2, just below, shows it step by step.

Tracer 2: TripAdvisor (you type Brighton, then 3)

Press Next step. The highlighted line is the one Java is running. Watch the variables and the terminal change. Green lines are comments; Java skips them. In the terminal, what you type appears after the question, and pressing Enter starts a new line.

1// Ask for the place (prompt stays on the same line).
2System.out.print("Where have you just visited? ");
3// Make the Scanner.
4Scanner myInput = new Scanner(System.in);
5// Read one word: the place.
6String place = myInput.next();
7// Ask for the stars.
8System.out.print("How many stars would you give it (1-5)? ");
9// Read one word: the rating, kept as TEXT, e.g. "3".
10String starNumber = myInput.next();
11// Show the place and the rating, same line.
12System.out.print(place + " (" + starNumber + " stars): ");
13
14// Switch with fall-through: Java jumps to the case that
15// matches starNumber and then runs every case below it,
16// because there is no break. "3" prints 3 stars.
17// Anything else (like "7") jumps straight to default,
18// which just ends the line.
19switch (starNumber) {
20 case "5": System.out.print("*");
21 case "4": System.out.print("*");
22 case "3": System.out.print("*");
23 case "2": System.out.print("*");
24 case "1": System.out.print("*");
25 default:
26 System.out.println("");
27}
28
29// Close the Scanner.
30myInput.close();
Variables
Terminal (what you see)

What will it print? Paris and 7

Guess first. Write your guess down. Then open the answer.

The user types Paris and then 7. What does TripAdvisor print?

Reveal answer

Paris (7 stars): and then a new line, with no stars. No case matches "7", so Java goes straight to default, which only ends the line.

5. Common Scanner methods

next, nextLine, nextInt, nextDouble

Once you have a Scanner (here myInput), you can read different kinds of input. The slides call this slightly advanced; the first four are the ones you will use most.

// Read one word (up to a space or Enter), as a String.
String word = myInput.next();
// Read the whole rest of the line, spaces included.
String line = myInput.nextLine();
// Read a whole number.
int age = myInput.nextInt();
// Read a decimal number.
double price = myInput.nextDouble();
MethodGives youExample
next()String: the next single wordString word = myInput.next();
nextLine()String: the rest of the lineString line = myInput.nextLine();
nextInt()int: a whole numberint age = myInput.nextInt();
nextDouble()double: a decimal numberdouble price = myInput.nextDouble();
nextFloat(), nextLong(), nextBoolean(), nextByte(), nextShort()other typesfor future reference

int and double

int and double. int is a whole number type; double is a decimal number type. nextInt() and nextDouble() give you real numbers you can do maths with. next() gives digits as text, not a number.
Show me the Python version
age = int(input())      # whole number
price = float(input())  # decimal number
word = input()          # text

Java int = Python int; Java double = Python float. In Python you convert the text yourself; Java’s Scanner does it for you.

6. A Scanner template for you

This week’s lab has a class called ScannerTemplate with the basic code you need to use a Scanner. It does nothing by itself. Duplicate it (right-click → Duplicate…) to start new programs that use Scanner.

// Tell Java we want to use the Scanner class.
import java.util.Scanner;

// The class (the box that holds the program).
// Give your copy a new name when you duplicate it.
public class ScannerTemplate
{
    // run() holds the program's instructions.
    public void run()
    {
        // Make a Scanner that reads the keyboard; call it myInput.
        Scanner myInput = new Scanner(System.in);

        // Put your own code here, for example:
        //     String city = myInput.next();

        // Close the Scanner when you have finished with it.
        myInput.close();
    }

    // Java starts here and calls run().
    public static void main(String[] args)
    {
        new ScannerTemplate().run();
    }
}

7. The while loop

Last week’s enhanced for loop ran its body once for each item in a list. A while loop is different: it does not need a list. It uses a condition (a test, like an if statement). As long as the condition is true, the body runs again. When the condition becomes false, the loop stops.

Think of a while loop as: “Keep doing this while the condition is true.”
// While the condition is true, run the body again.
// The loop stops as soon as the condition is false.
while (condition) {
    // loop body
}
while. The test goes in round brackets; the body goes in curly brackets. Java checks the test; if it is true, it runs the body and then goes back to check again. If it is false, it skips past the closing } and carries on. The shape is the same as an if statement: just replace if with while.
Show me the Python version
while condition:
    # loop body
    ...

Same as Python’s while, with round brackets round the test and curly brackets instead of a colon and indentation.

Important: always make sure the condition can become false one day, or the loop runs forever.

8. Making sure the loop stops

The condition is checked every time round. Its code stays the same, but the values it checks can change, and that is what lets the loop stop. If the values never change, the body runs forever: an infinite loop.

Always check that your loop has a way to stop before you run it.

9. While example 1: HelloEverybody (stopping with user input)

The HelloEverybody program

HelloEverybody adds a while loop to SayHello. It keeps asking for names until the name is the word “bye”. It starts like SayHello: print a prompt, read the first answer into name. Then it goes into the while loop, where name is the loop variable.

// Ask for the first name, before the loop.
System.out.print("What is your name (bye to exit)? ");
// Make a Scanner that reads the keyboard.
Scanner myInput = new Scanner(System.in);
// Read the whole line typed: the first name.
// name is the loop variable.
String name = myInput.nextLine();

// While loop: repeat while name is NOT "bye".
// It stops when the user types bye (in lower case).
while (!name.equals("bye")) {
    // Greet the current name.
    System.out.println("Hello " + name + ", nice to meet you");
    // Ask again.
    System.out.print("What is your name (bye to exit)? ");
    // IMPORTANT: update the loop variable, so bye can stop it.
    name = myInput.nextLine();
}

// After the loop: close the Scanner.
myInput.close();

The last line of the loop body asks for another name and stores it in name. That updates the loop variable. When the user types bye, the test becomes false and the loop stops. Without that line, it would never stop. Tracer 3, just below, shows it step by step.

! (not)

! (not). ! means “not”. !name.equals("bye") is true while name is not “bye”.
Show me the Python version
while name != "bye":
    ...
# or: while not name == "bye":

Python writes != or the word not. Java puts ! in front of the test.

.equals versus ==

.equals versus ==. To compare Strings in Java, write name.equals("bye"). Do not write name == "bye": == checks whether two things are the very same object in memory, and can say false even when the letters match. Use == for numbers.
Show me the Python version
print(name == "bye")   # Python == compares the letters

In Python == works for text. In Java, always use .equals for Strings. It also checks capitals: "Bye" is not "bye".

Tracer 3: HelloEverybody (you type Tom, Harry, bye)

Press Next step. The highlighted line is the one Java is running. Watch the variables and the terminal change. Green lines are comments; Java skips them. In the terminal, what you type appears after the question, and pressing Enter starts a new line.

1// First prompt, before the loop.
2System.out.print("What is your name (bye to exit)? ");
3// Make the Scanner.
4Scanner myInput = new Scanner(System.in);
5// Read the first name: the loop variable.
6String name = myInput.nextLine();
7// Loop while name is NOT "bye"; stops when it is.
8while (!name.equals("bye")) {
9 // Greet the current name.
10 System.out.println("Hello " + name + ", nice to meet you");
11 // Ask again.
12 System.out.print("What is your name (bye to exit)? ");
13 // Update the loop variable.
14 name = myInput.nextLine();
15}
16// After the loop.
17myInput.close();
Variables
Terminal (what you see)

What will it print? The missing line

Guess first. Write your guess down. Then open the answer.

Someone deletes the last line of the HelloEverybody loop (name = myInput.nextLine();). The user types Tom.

// Read the first name.
String name = myInput.nextLine();
// While loop: repeat while name is not "bye".
while (!name.equals("bye")) {
    // Greet the current name.
    System.out.println("Hello " + name + ", nice to meet you");
    // Ask again (but the answer is never read!).
    System.out.print("What is your name (bye to exit)? ");
}
Reveal answer

It prints Hello Tom, nice to meet you followed by the question, over and over, forever. This is an infinite loop. name is never updated, so it is always "Tom" and the test is always true. It never waits for you to type again. (In BlueJ, stop it with right-click on the striped bar at the bottom right → Reset Java Virtual Machine.)

10. Challenge: special replies for certain names

In HelloEverybody everyone gets the same greeting. The lecture’s challenge: if the name is Tom, ask “Do you also have a friend called Jerry?”; if it is Harry, ask “How is Ron doing?”; everyone else keeps the normal greeting. Hint: combine the while loop with if-else (or switch-case).

// Inside the while loop: choose a reply.
// Exactly one branch runs: Tom, Harry, or anyone else.
if (name.equals("Tom")) {
    // runs only when name is Tom
    System.out.println("Do you also have a friend called Jerry?");
} else if (name.equals("Harry")) {
    // runs only when name is Harry
    System.out.println("How is Ron doing?");
} else {
    // runs for anyone else: the normal greeting
    System.out.println("Hello " + name + ", nice to meet you");
}
if / else if / else. Java checks each test in order and runs the first block whose test is true, then skips the rest. If none is true, the else block runs. Each test goes in round brackets, each block in curly brackets.
Show me the Python version
if name == "Tom":
    print("Do you also have a friend called Jerry?")
elif name == "Harry":
    print("How is Ron doing?")
else:
    print("Hello " + name + ", nice to meet you")

Java else if = Python elif. Same order, same “first true one wins” rule.

11. While example 2: Santa (stopping with a calculation)

The Santa program

Loops based on a calculation are often simpler. Santa prints Ho! Ho! Ho! Ho! Ho!. The loop variable is x, a whole number. Before the loop, x is set to 5. The condition is x > 0, so the loop stops when x reaches 0. The body prints “Ho!” and takes 1 off x.

// The class that holds the Santa program.
public class Santa
{
    // run() holds the program's instructions.
    public void run()
    {
        // The counter: number of times Santa says "Ho!".
        int x = 5;

        // While loop: repeat while x is bigger than 0.
        // x goes down by 1 each time, so it stops at 0.
        while (x > 0)
        {
            // print keeps all the Ho!s on one line.
            System.out.print("Ho! ");
            // Take 1 off x, so the loop can stop.
            x = x - 1;
        }

        // After the loop: end the line.
        System.out.println();
    }

    // Java starts here and calls run().
    public static void main(String[] args){new Santa().run();}
}

print keeps all the Ho!s on the same line; the println() after the loop moves to a new line at the end. Tracer 4, just below, shows it step by step.

int and >

int and >. int x = 5; makes a whole-number variable called x and puts 5 in it. x > 0 is a test: true when x is bigger than 0.
Show me the Python version
x = 5
print(x > 0)   # True

Same > as Python. Java makes you write the type int the first time.

x = x - 1;

x = x - 1; It looks like an equation, but it is an instruction: “take the value in x, subtract 1, and store the answer back in x”.
Show me the Python version
x = x - 1

Identical in Python (apart from the semicolon).

x-- and x++

x-- and x++. Shortcuts: x--; takes 1 off x (decrement); x++; adds 1 to x (increment). Counters like these are the most common way to control calculation-based loops.
Show me the Python version
x -= 1   # Python has no x--
x += 1   # or x++

Python has no ++ or --; use -= 1 and += 1.

Tracer 4: Santa (counting down)

Press Next step. The highlighted line is the one Java is running. Watch the variables and the terminal change. Green lines are comments; Java skips them. In the terminal, what you type appears after the question, and pressing Enter starts a new line.

1// The class that holds the Santa program.
2public class Santa
3{
4 // run() holds the program's instructions.
5 public void run()
6 {
7 // The counter: number of times Santa says "Ho!".
8 int x = 5;
9
10 // While loop: repeat while x is bigger than 0.
11 // x goes down by 1 each time, so it stops at 0.
12 while (x > 0)
13 {
14 // print keeps all the Ho!s on one line.
15 System.out.print("Ho! ");
16 // Take 1 off x, so the loop can stop.
17 x = x - 1;
18 }
19
20 // After the loop: end the line.
21 System.out.println();
22 }
23
24 // Java starts here and calls run().
25 public static void main(String[] args){new Santa().run();}
26}
Variables
Terminal (what you see)

What will it print? Three Ho!s

Guess first. Write your guess down. Then open the answer.

What will this print?

// The counter starts at 3.
int x = 3;
// While loop: repeat while x is bigger than 0;
// x goes down by 1 each time.
while (x > 0) {
    // print: stay on the same line
    System.out.print("Ho! ");
    // take 1 off x
    x = x - 1;
}
// After the loop: print a message and end the line.
System.out.println("Merry Christmas");
Reveal answer

Ho! Ho! Ho! Merry Christmas – all on one line. x goes 3, 2, 1, then 0 stops the loop. The print calls keep everything on one line until println.

What will it print? Counting up

Guess first. Write your guess down. Then open the answer.

What will this print?

// The counter starts at 0.
int x = 0;
// While loop: repeat while x is less than 3;
// x goes up by 1 each time.
while (x < 3) {
    // print x and a space, same line
    System.out.print(x + " ");
    // add 1 to x
    x++;
}
Reveal answer

0 1 2 . x starts at 0. It prints 0, 1 and 2. When x becomes 3, 3 < 3 is false, so 3 is never printed. x++ is the same as x = x + 1.

12. While loop notes, and the Santa challenge

Input-based and calculation-based loops

  • Input-based while loops are unpredictable: they depend on what the user types.
  • Calculation-based while loops are predictable: they always run the same way.
  • General rule: code is predictable unless it uses something from outside, such as user input.
  • You can combine them: a calculation loop that runs a number of times the user chooses (see the DrawSquare exercise).
  • Java also has a random number generator, which makes programs unpredictable even without input.

Just for fun: tell Santa how many Ho!s

Challenge part 1: ask the user how many times Santa should say “Ho!”, instead of using a fixed number. Part 2: keep asking until the user enters 0 or a negative number. Hint: use two while loops: one updated by user input, the other by calculation. Don’t worry if it feels hard. The slide notes give the code for part 1 (shown here with comments):

// Tell Java we want to use the Scanner class.
// (The slide notes leave this line out; you need it.)
import java.util.Scanner;

// The class that holds the challenge program.
public class Santa1 {
    // run() holds the program's instructions.
    public void run() {
        // Ask how many Ho!s (print keeps the answer on this line).
        System.out.print("How many Hos do you want to Santa to say? ");
        // Make a Scanner that reads the keyboard.
        Scanner myInput = new Scanner(System.in);
        // Read a whole number and keep it in number.
        int number = myInput.nextInt();

        // Calculation loop: repeat while number is above 0.
        // number goes down by 1 each time, so it stops at 0.
        while(number>0){
            // Say Ho! once, staying on the same line.
            System.out.print("Ho! ");
            // Take 1 off number, so the loop can stop.
            number=number-1;
        }
    }

    // Java starts here and calls run().
    public static void main(String[] args) {
        new Santa1().run();
    }
}
myInput.nextInt(). Reads a whole number from the keyboard and gives it back as an int, so you can compare it with > and do maths with it.
Show me the Python version
number = int(input("How many Hos? "))

Python reads text and you convert it with int(). Java’s nextInt() reads and converts in one step.

13. Summary

Ideas 1–13 follow the lecture slides in order.

The lab: what you will do

From the lab instructions at the end of the lecture slides (slide 31). Your Lab Walkthrough page takes you through them step by step.

  1. Download the project. Get scannerWhile.zip and open it in BlueJ.
  2. Explore the example classes. Open and read SayHello, TripAdvisor, ScannerTemplate, HelloEverybody and Santa. Run each one.
  3. Work on the exercises (classes starting with Ex_). Follow the instructions at the top of each file.
    • Ex_QueenBot – duplicate HelloEverybody as QueenBot. Inside the loop, also ask “What do you do?” and comment on the job. Optional: use a switch for different jobs.
    • Ex_EstateAgent_To_HouseTour – turn last week’s EstateAgent into HouseTour. A while loop asks which room to visit next, until the user ends the tour. Optional: use a switch for the room messages.
    • Ex_DrawSquare (extension – don’t worry if you can’t do it) – read a size and draw a square of stars, for example 5 lines of 5 stars.
  4. Check your solutions (optional). Model answers start with Sol1_, Sol2_ and so on. Only look after you have tried.
  5. Challenging exercise (for experienced students): Ex_CityRatings_Challenging. Three solution versions are given; each explains its differences at the top.

Quiz: 8 questions

Click an answer. You find out straight away. Your answers are saved in this browser.

Score: 0 / 8

Q1. In Java, which channel is the keyboard?

Q2. Which Scanner method reads a whole line of text, spaces included?

Q3. The code says String city = myInput.next(); and the user types New York. What is in city?

Q4. Why does SayHello use print, not println, for its prompt?

Q5. In while (!name.equals("bye")), what does the ! mean?

Q6. int x = 5; while (x > 0) { System.out.print("Ho! "); x = x - 1; } How many Ho!s?

Q7. What usually causes an infinite loop?

Q8. Which kind of while loop always runs the same way every time?

CI401 Week 2 · Sunday prep · made from the Week 2 slides and the scannerWhile lab files.