Use this page while you work in BlueJ. Tick each step when you finish it; your ticks are saved in this browser. Answers stay hidden until you click “Reveal answer”. Slides: Input and Repetition - Scanner + While Loop.pptx

0 Put this page and the chat side by side

You will have this page on the left and the course chat on the right. Ask the chat whenever you are stuck.

  1. Click this button:
    It opens the chat in a new tab and then tries to bring you back here. Most browsers still switch to the new tab anyway. That is normal: just click back on this tab.
  2. Now put the two tabs side by side:
    Chrome: right-click this tab at the top of the window → Add tab to new split view → then pick the Grok tab.
    Edge: click the three dots (…) next to the address bar → Split screen → then select the Grok tab.

  3. Type your questions into the chat on the right. This page has no ask box.
Stuck? No split option in your browser? Just drag the two windows so each fills half the screen.
Reveal answer

You should see this walkthrough on the left and the Grok chat on the right.

1 Open BlueJ and the scannerWhile project

  1. Download scannerWhile.zip (it is in the “Lecture and lab materials” folder). Do not unzip it.
  2. Open BlueJ.
  3. Click Project → Open ZIP/JAR... → choose scannerWhile.zip → Open.
  4. You see orange boxes. Each box is one class.
  5. Click Compile on the left. The striped boxes become plain.
New word: class. A class is the container for a Java program. All Java code lives inside a class. In BlueJ each orange box is one class, saved in its own .java file.
New word: compile. Compiling means Java checks your code and turns it into something the computer can run. Python does not need this step. If there is a mistake, BlueJ will not compile and shows an error at the bottom of the editor.

Examples have normal names (SayHello, HelloEverybody, Santa). Exercises start with Ex_. Model answers start with Sol1_, Sol2_, Sol3_. Drag boxes around if you like; your layout may look different from the slide.

Stuck? Cannot find Open ZIP/JAR? It is under the Project menu at the very top of the BlueJ window. If BlueJ says the project is read-only, unzip it into your Documents folder and use Project → Open Project instead.
Reveal answer

You should see 18 class boxes including ScannerTemplate, SayHello, TripAdvisor, HelloEverybody, Santa, Ex_QueenBot, Ex_EstateAgent_To_HouseTour, Ex_DrawSquare and Ex_CityRatings_Challenging, plus the Sol classes. After Compile, none of them are striped.

2 Read ScannerTemplate: the skeleton of every program

  1. Double-click ScannerTemplate to open its code.
  2. Read it top to bottom with the notes below.
Java
import java.util.Scanner;

public class ScannerTemplate
{
    public void run()
    {
        Scanner myInput = new Scanner(System.in);
        // your code goes here
        myInput.close();
    }

    public static void main(String[] args)
    {
        new ScannerTemplate().run();
    }
}
Python
# no import needed: input() is built in

class ScannerTemplate:
    def run(self):
        # your code goes here
        pass

ScannerTemplate().run()
  • import java.util.Scanner; is like a Python import: it lets you use the Scanner class.
  • Semicolon ; ends every Java instruction. Python uses the end of the line. Forget it and BlueJ says ';' expected.
  • Curly brackets { } show where the class, a method, or a loop starts and ends. Python uses a colon and indentation. Every { needs a matching }.
  • Scanner myInput = new Scanner(System.in); makes a Scanner called myInput that reads the keyboard (System.in).
  • myInput.close(); closes it when you have finished.
New word: semicolon. The ; at the end of a Java statement. It means “this instruction ends here”.
New word: method. A method is a named block of code, like a Python def. Here there are two: run() and main(). Java starts at main, which calls run.
New word: array. String[] args in main is an array: a fixed-length list of Strings. You do not need it this week. Just copy that line as it is.
Stuck? It is fine not to understand public static void yet. Copy those lines as they are; you only write your own code inside run().
Reveal answer

This class does nothing when you run it. It is only a starting point: you put your own code between the Scanner line and the close line.

3 Run SayHello and type your name

  1. Right-click SayHello → click void main(String[] args) → click OK.
  2. The terminal window opens with What is your name?.
  3. Click in the bottom of the terminal, type Java, press Enter.
  4. Run it again and type New York. Look carefully at the reply.
New word: terminal. The terminal is the text window where the program prints its output and where you type input. In BlueJ you type in the bottom part of it.
Java
System.out.print("What is your name? ");
Scanner myInput = new Scanner(System.in);
String name = myInput.next();
System.out.println("Hello " + name + ", nice to meet you");
myInput.close();
Python
name = input("What is your name? ")
print("Hello " + name + ", nice to meet you")

print versus println. System.out.print prints and stays on the same line (Python print(..., end="")). System.out.println prints and then moves to a new line (a normal Python print). The prompt uses print so your answer appears right next to the question.

Java
System.out.print("Hi ");
System.out.println("there");
Python
print("Hi ", end="")
print("there")

String name makes a text variable. Java needs the type in front of a new variable; Python does not.

Stuck? Nothing happens when you type? Click inside the terminal first, at the bottom. The program is waiting at myInput.next() until you press Enter.
Reveal answer

With Java: Hello Java, nice to meet you.

With New York: Hello New, nice to meet you. next() reads only one word, up to the first space. nextLine() would read the whole line.

4 Run TripAdvisor and meet switch / case / break

  1. Run TripAdvisor (right-click → void main → OK).
  2. Type Brighton, Enter, then 3, Enter.
  3. Run it again with 5, then again with 7. Predict each answer before you press Enter.
  4. Open the code and find the switch.
Java
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:
        System.out.println("");
}
Python
# Python's match never falls through,
# so the nearest is:
if starNumber in ["1","2","3","4","5"]:
    print("*" * int(starNumber), end="")
print("")

switch / case / break. switch (x) looks at x and jumps to the case with the same value. Each case ends with a colon :. break means “stop and leave the switch”. default is the “anything else” case, like a final else.

Here there is no break after the cases. So after jumping in, Java falls through and runs every line below. That is why 3 prints three stars. The cases have quotes ("3") because next() gives text, not a number.

Stuck? Seeing no stars? Check you typed just a number 1 to 5 with no spaces.
Reveal answer

3 → Brighton (3 stars): ***
5 → Brighton (5 stars): *****
7 → Brighton (7 stars): with no stars. No case matches, so only default runs.

5 Run HelloEverybody: your first while loop

  1. Run HelloEverybody. Type Tom, then Harry, then bye.
  2. Open the code and find the while line.
  3. Find the line inside the loop that changes name.
Java
String name = myInput.nextLine();
while (!name.equals("bye")) {
    System.out.println("Hello " + name + ", nice to meet you");
    System.out.print("What is your name (bye to exit)? ");
    name = myInput.nextLine();
}
Python
name = input("What is your name (bye to exit)? ")
while name != "bye":
    print("Hello " + name + ", nice to meet you")
    name = input("What is your name (bye to exit)? ")
  • while (test) { ... } repeats the body while the test is true. Test in round brackets, body in curly brackets.
  • ! means not.
  • .equals versus ==. To compare text in Java, write name.equals("bye"). Do not write name == "bye". == checks whether two things are the very same object in memory, so it can say false even when the letters match. In Python == is fine for text; in Java always use .equals for Strings.
  • name is the loop variable. The last line updates it. Without that line the loop never stops.
Stuck? Typed Bye or BYE and it did not stop? .equals checks exact letters, capitals included. Type bye in lower case.
Reveal answer

It greets Tom and Harry, then stops when you type bye (bye itself is not greeted). The update line is name = myInput.nextLine();, the last line in the loop body.

6 Run Santa: a loop that counts down

  1. Run Santa. It needs no input.
  2. Open the code. Change int x = 5; to int x = 3;. Compile and run.
  3. Change x = x - 1; to x--;. Compile and run. Same result?
  4. Put it back to 5 when you are done.
Java
int x = 5;
while (x > 0)
{
    System.out.print("Ho! ");
    x = x - 1;     // or: x--;
}
System.out.println();
Python
x = 5
while x > 0:
    print("Ho! ", end="")
    x = x - 1      # or: x -= 1
print()

int means a whole number. x = x - 1; is not maths: it means “take x, subtract 1, store it back in x”. x-- is a shortcut for that; x++ adds 1. Python has no ++ or --.

This loop is calculation-based, so it is predictable. HelloEverybody was input-based, so it depends on what you type.

Stuck? Program never ends (an infinite loop)? Right-click the striped bar at the bottom right of the BlueJ window and choose Reset Java Virtual Machine. Then check that the loop changes x.
Reveal answer

x = 5 → Ho! Ho! Ho! Ho! Ho! . x = 3 → Ho! Ho! Ho! . x--; gives exactly the same as x = x - 1;.

7 Exercise: QueenBot (part 1, name and job)

The Queen asks each person their name and what they do, then comments on it.

  1. Right-click HelloEverybody → Duplicate... → type QueenBot → OK.
  2. Open QueenBot. Check the top says public class QueenBot and main says new QueenBot().run();. Fix any that still say HelloEverybody.
  3. Under the line that reads name, add a new variable: String occupation = "";
  4. Inside the while loop, after the hello: print the prompt what do you do? and read the job into occupation.
  5. Print a comment such as occupation + " is such an interesting job!".
  6. Keep the last two lines of the loop (ask for a name, update name). Compile, run, test with two people, then bye.
Java
String occupation = "";
...
System.out.print("what do you do? ");
occupation = myInput.nextLine();
System.out.println(occupation + " is such an interesting job!");
Python
occupation = ""
...
occupation = input("what do you do? ")
print(occupation + " is such an interesting job!")

The exercise file says myScanner.next(), but in HelloEverybody the Scanner is called myInput. Use myInput.

Stuck? Second name comes out empty, or the loop seems to skip a question? You probably mixed next() and nextLine(). next() leaves the Enter behind, and the next nextLine() reads that empty bit. Use nextLine() everywhere in this program (or next() everywhere).
Reveal answer

One working version (compare with Sol1_QueenBot):

import java.util.Scanner;

public class QueenBot
{
    public void run() {
        System.out.print("What is your name (bye to exit)? ");
        Scanner myInput = new Scanner(System.in);
        String name = myInput.nextLine();
        String occupation = "";

        while (!name.equals("bye")) {
            System.out.print("Hello " + name + ", what do you do? ");
            occupation = myInput.nextLine();
            System.out.println(occupation + " is such an interesting job!");

            System.out.print("What is your name (bye to exit)? ");
            name = myInput.nextLine();
        }
        myInput.close();
    }

    public static void main(String[] args) {
        new QueenBot().run();
    }
}

Test: Ann, teacher, bye → Hello Ann, what do you do? teacher then teacher is such an interesting job!, then it stops.

8 Exercise: QueenBot (part 2, a switch for jobs)

The exercise says you could also make the Queen say different things for different jobs.

  1. In QueenBot, replace the single comment line with a switch (occupation).
  2. Add case "queen": and case "student": with their own replies, each ending in break;.
  3. Add default: with the general reply.
  4. Compile and test with student, queen and chef.
Java
switch (occupation) {
    case "student":
        System.out.println("I hope you are enjoying your studies!");
        break;
    default:
        System.out.println(occupation + " is such an interesting job!");
}
Python
match occupation:
    case "student":
        print("I hope you are enjoying your studies!")
    case _:
        print(occupation + " is such an interesting job!")

This time you want break. Without it, a student would get the student reply and the default reply.

Stuck? Getting two replies at once? You forgot a break; at the end of a case.
Reveal answer

The switch part (compare with Sol2_QueenBot):

switch (occupation) {
    case "queen":
        System.out.println("Oh, God bless queen!");
        break;
    case "student":
        System.out.println("I hope you are enjoying your studies!");
        break;
    default:
        System.out.println(occupation + " is such an interesting job!");
}

student → I hope you are enjoying your studies!; chef → chef is such an interesting job!

9 Exercise: HouseTour (from EstateAgent)

Last week EstateAgent walked through a fixed list of rooms. Now the user chooses each room until they end the tour.

  1. Open Ex_EstateAgent_To_HouseTour and read the old EstateAgent code in the comment block.
  2. Right-click ScannerTemplate → Duplicate... → name it HouseTour. Fix the class name and the new ...().run() line if needed.
  3. Inside run(), after the Scanner line: print Which room would you like to see (bye to exit)? and read String room = myInput.next();
  4. Write while (!room.equals("bye")) { ... }.
  5. Inside the loop, copy the room comments (the if / else if / else chain) from EstateAgent.
  6. At the end of the loop body, ask again and update room. Compile and test.

Enhanced for (in the old code). for (String room : rooms) runs once for each item in the array rooms, putting it in room. You are replacing it with a while loop and the Scanner.

Java
String[] rooms = {"hall", "kitchen"};
for (String room : rooms) {
    System.out.println(room);
}
Python
rooms = ["hall", "kitchen"]
for room in rooms:
    print(room)

if / else if / else. Java tests each condition in order and runs the first one that is true. Python writes elif; Java writes else if. Each test goes in ( ), each block in { }.

Java
if (room.equals("kitchen")) {
    System.out.print("Can you smell the coffee? ");
} else if (room.equals("hall")) {
    System.out.print("Nice and big windows.");
} else {
    System.out.print("What is this room used for?");
}
Python
if room == "kitchen":
    print("Can you smell the coffee? ", end="")
elif room == "hall":
    print("Nice and big windows.", end="")
else:
    print("What is this room used for?", end="")
Stuck? Red error cannot find symbol: room? You need String room the first time (before the loop) and just room = ... inside the loop. Keep myInput.close(); after the loop, not inside it.
Reveal answer

One working version (compare with Sol1_HouseTour_WhileIfElse):

import java.util.Scanner;

public class HouseTour {
    public void run() {
        System.out.print("Which room would you like to see (bye to exit)? ");
        Scanner myInput = new Scanner(System.in);
        String room = myInput.next();

        while (!room.equals("bye")) {
            System.out.print("Here we are in the " + room + ". ");
            if (room.equals("kitchen")) {
                System.out.print("Can you smell the coffee? ");
            } else if (room.equals("bedroom")) {
                System.out.print("Plenty of room for all your clothes.");
            } else if (room.equals("lounge")) {
                System.out.print("Notice the original fireplace.");
            } else if (room.equals("hall")) {
                System.out.print("Nice and big windows.");
            } else {
                System.out.print("What is this room used for?");
            }
            System.out.println();
            System.out.print("Which room would you like to see (bye to exit)? ");
            room = myInput.next();
        }
        myInput.close();
    }

    public static void main(String[] args) {
        new HouseTour().run();
    }
}

Test: kitchen → Here we are in the kitchen. Can you smell the coffee?; attic → ... What is this room used for?; bye ends the tour.

10 Exercise: HouseTour with a switch (optional part 3)

  1. Change the if / else if / else chain in HouseTour to a switch (room).
  2. One case per room, each ending in break;. Use default: for any other room.
  3. Compile and test with the same rooms as before. The output should not change.
Java
switch (room) {
    case "kitchen":
        System.out.print("Can you smell the coffee? ");
        break;
    default:
        System.out.print("What is this room used for?");
}
Python
match room:
    case "kitchen":
        print("Can you smell the coffee? ", end="")
    case _:
        print("What is this room used for?", end="")
Stuck? Kitchen also prints “Plenty of room for all your clothes.”? A break; is missing, so it fell through into the next case.
Reveal answer

The switch (compare with Sol2_HouseTour_WhileSwitch):

switch (room){
    case "kitchen":
        System.out.print("Can you smell the coffee? ");
        break;
    case "bedroom":
        System.out.print("Plenty of room for all your clothes.");
        break;
    case "lounge":
        System.out.print("Notice the original fireplace.");
        break;
    case "hall":
        System.out.print("Nice and big windows.");
        break;
    default : System.out.print("What is this room used for?");
}

11 Extension: DrawSquare (do not worry if you cannot do it)

Draw a square of stars. If the user types 5, show 5 lines of 5 stars.

  1. Open Ex_DrawSquare. The StarRating code from last week is copied in the comment block.
  2. Click New Class..., name it DrawSquare, choose Class, OK. Open it, delete everything, and paste the StarRating code from the comment. Rename StarRating to DrawSquare in both places.
  3. Read the size with int stars = myInput.nextInt(); (you will need the Scanner import and line from ScannerTemplate).
  4. Make a counter int line = 0; and a loop while (line < stars) { ... line++; } around the switch.
  5. Test with 3 and 5. Then try 7. What goes wrong?
  6. Fix it: swap the switch for a second while loop inside the first one, with its own counter x.
Java
int stars = myInput.nextInt();
int line = 0;
while (line < stars) {
    int x = 0;
    while (x < stars) {
        System.out.print("*");
        x++;
    }
    System.out.println();
    line++;
}
Python
stars = int(input("How many stars? "))
line = 0
while line < stars:
    x = 0
    while x < stars:
        print("*", end="")
        x += 1
    print()
    line += 1

nextInt() reads a whole number, so you can compare it with <. A loop inside a loop needs different loop variables (line and x).

Stuck? Only one long line of stars? Your System.out.println(); must be inside the outer loop but after the inner loop. Endless stars? Check that x++ and line++ are there.
Reveal answer

With the switch version (Sol1_DrawSquare_WhileSwitch), 7 prints 7 empty lines, because the switch only has cases 1 to 5. The fixed version (Sol2_DrawSquare_2Whiles):

import java.util.Scanner;

public class DrawSquare
{
    public void run() {
        System.out.print("How many stars? ");
        Scanner myInput = new Scanner(System.in);
        int stars = myInput.nextInt();

        int line = 0;
        while (line < stars) {
            int x = 0;
            while (x < stars) {
                System.out.print("*");
                x++;
            }
            System.out.println();
            line++;
        }
        myInput.close();
    }

    public static void main(String[] args) {
        new DrawSquare().run();
    }
}

Input 3 →

***
***
***

12 Check your work against the Sol_ classes

  1. Only now, open Sol1_QueenBot and Sol2_QueenBot. Compare with yours.
  2. Open Sol1_HouseTour_WhileIfElse and Sol2_HouseTour_WhileSwitch.
  3. If you tried DrawSquare: open Sol1_DrawSquare_WhileSwitch and Sol2_DrawSquare_2Whiles.
  4. Run each model answer once. Note one thing that is different from yours.
Stuck? Your code looks different but works? That is fine. There is more than one right answer; that is why there are Sol1 and Sol2.
Reveal answer

Sol1 versions use if / else (or a single comment); Sol2 versions use switch (or, for DrawSquare, two while loops). Sol1_QueenBot reads the first name with nextLine() and later names with next(), so stick to one-word names when you run it.

13 Optional: special replies for Tom and Harry optional

Lecture challenge (slide 23).

  1. Duplicate HelloEverybody and call it SpecialNames.
  2. Inside the loop, replace the hello line with an if / else if / else: Tom → “Do you also have a friend called Jerry?”, Harry → “How is Ron doing?”, anyone else → the normal greeting.
  3. Test with Tom, Harry, Ann, bye.
Stuck? Tom gets the normal greeting? Check the capital T, and that you used .equals("Tom"), not ==.
Reveal answer

No model answer was given for this one. One way:

while (!name.equals("bye")) {
    if (name.equals("Tom")) {
        System.out.println("Do you also have a friend called Jerry?");
    } else if (name.equals("Harry")) {
        System.out.println("How is Ron doing?");
    } else {
        System.out.println("Hello " + name + ", nice to meet you");
    }
    System.out.print("What is your name (bye to exit)? ");
    name = myInput.nextLine();
}

14 Optional: tell Santa how many Ho!s optional

Just-for-fun challenge (slide 27).

  1. Duplicate ScannerTemplate as Santa1. Ask how many Ho!s, read it with nextInt(), then count it down in a while loop.
  2. Then make Santa2: keep asking until the user types 0 or a negative number. Use two while loops.
Stuck? Error cannot find symbol: class Scanner? Add import java.util.Scanner; at the very top. (The code in the slide notes is missing this line.)
Reveal answer

Santa2 (based on the slide notes; the outer test is number > 0 so a negative number also stops it):

System.out.print("How many Hos do you want Santa to say (0 exit)? ");
Scanner myInput = new Scanner(System.in);
int number = myInput.nextInt();

while (number > 0) {          // input-based
    while (number > 0) {      // calculation-based
        System.out.print("Ho! ");
        number = number - 1;
    }
    System.out.println("");
    System.out.print("How many Hos do you want Santa to say (0 exit)? ");
    number = myInput.nextInt();
}
myInput.close();

15 Optional: City Ratings (challenging, for experienced students) optional

  1. Open Ex_CityRatings_Challenging and read the instructions in the comment at the top.
  2. Use the enhanced for loop over cities. For each city ask “Have you visited ...? (yes/no)”.
  3. If yes, ask for stars and print them (fall-through switch, or an if-else chain). If no, print “[city] is nice, you should visit someday!”.
  4. Then compare with Sol1, Sol2 and Sol3_CityRatings. Each one explains at the top what it does differently.
Stuck? The model answers use y/n, not yes/no. equalsIgnoreCase is .equals that ignores capitals.
Reveal answer

Core of version 1 (Sol1_CityRatings):

for (String city : cities) {
    System.out.print("Have you visited " + city + "? (y/n): ");
    String yesOrNo = myInput.next();
    if (yesOrNo.equalsIgnoreCase("y")) {
        System.out.print("How many stars (1-5)? ");
        String stars = myInput.next();
        System.out.print(city + " (" + stars + " stars): ");
        switch (stars) {
            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("*");
            break;
            default:
        }
        System.out.println();
    } else if (yesOrNo.equalsIgnoreCase("n")) {
        System.out.println(city + " is nice, you should visit someday!");
    }
}

Version 2 repeats the y/n question until it is valid. Version 3 also repeats the star question and lets you type exit at any time.

How to submit this lab

No lab submission was found for this week. Every part of the CI401 course on Student Central was checked on 17 October 2026: the week pages, the slides, the announcements, Assessment and Feedback Information, Assessment Submission Points, the module roadmap and the assessment brief. None of them gives any steps for submitting, demonstrating or getting sign-off for lab work. So there is nothing to hand in for this lab.

This matches what the Module Overview slides say (slide 12): “Weekly lab exercises are practice activities - they are not directly assessed. They are there to help you practise the programming techniques covered in the module and prepare you for the coursework.” (Module Overview slides)

What the lab is practice for: the coursework

  • The module’s only assessment is the coursework project.
  • Deadline: 22 January 2027 at 14:00.
  • Where: online, through MyStudies.
  • What you hand in: your project code as a zip file, plus a technical report (PDF or Word).
  • Full details are expected around Week 8.

Lab work is good practice for it. Keep your own lab code (the unzipped project folder BlueJ made), so you can look back at it later.

If you ever need to hand in anything based on this week’s lab, use the Original lab code (the lecturer’s zip), not the commented version.

AI rule for the coursework. The coursework is rated RED for AI: using generative AI is not allowed, apart from checking spelling and grammar. Check the assessment brief (in the Assessment Information area on MyStudies) for the exact rules.

You are done when

  • QueenBot runs: you type Ann, teacher, Ben, student, bye and it greets both people, comments on both jobs, and then stops.
  • HouseTour runs: kitchen gives “Can you smell the coffee?”, attic gives “What is this room used for?”, and bye ends the tour.
  • Both compile with no errors, and you can say in one sentence which line in each loop updates the loop variable.
  • (Extension, only if you tried it) DrawSquare with 4 prints 4 lines of ****.

Commented versions of every example and exercise are in CI401_Week2_Commented_Lab.zip. Slides: Input and Repetition - Scanner + While Loop.pptx.