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.
- 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. - 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.
- Type your questions into the chat on the right. This page has no ask box.
Reveal answer
You should see this walkthrough on the left and the Grok chat on the right.
1 Open BlueJ and the scannerWhile project
- Download scannerWhile.zip (it is in the “Lecture and lab materials” folder). Do not unzip it.
- Open BlueJ.
- Click Project → Open ZIP/JAR... → choose
scannerWhile.zip→ Open. - You see orange boxes. Each box is one class.
- Click Compile on the left. The striped boxes become plain.
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.
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
- Double-click ScannerTemplate to open its code.
- Read it top to bottom with the notes below.
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();
}
}# 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 Pythonimport: 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 calledmyInputthat reads the keyboard (System.in).myInput.close();closes it when you have finished.
; at the end of a Java statement. It means “this instruction ends here”.def. Here there are two: run() and main(). Java starts at main, which calls run.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.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
- Right-click SayHello → click void main(String[] args) → click OK.
- The terminal window opens with
What is your name?. - Click in the bottom of the terminal, type
Java, press Enter. - Run it again and type
New York. Look carefully at the reply.
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();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.
System.out.print("Hi ");
System.out.println("there");print("Hi ", end="")
print("there")String name makes a text variable. Java needs the type in front of a new variable; Python does not.
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
- Run TripAdvisor (right-click → void main → OK).
- Type
Brighton, Enter, then3, Enter. - Run it again with
5, then again with7. Predict each answer before you press Enter. - Open the code and find the
switch.
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'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.
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
- Run HelloEverybody. Type
Tom, thenHarry, thenbye. - Open the code and find the
whileline. - Find the line inside the loop that changes
name.
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();
}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..equalsversus==. To compare text in Java, writename.equals("bye"). Do not writename == "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.equalsfor Strings.nameis the loop variable. The last line updates it. Without that line the loop never stops.
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
- Run Santa. It needs no input.
- Open the code. Change
int x = 5;toint x = 3;. Compile and run. - Change
x = x - 1;tox--;. Compile and run. Same result? - Put it back to 5 when you are done.
int x = 5;
while (x > 0)
{
System.out.print("Ho! ");
x = x - 1; // or: x--;
}
System.out.println();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.
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.
- Right-click HelloEverybody → Duplicate... → type
QueenBot→ OK. - Open QueenBot. Check the top says
public class QueenBotand main saysnew QueenBot().run();. Fix any that still say HelloEverybody. - Under the line that reads
name, add a new variable:String occupation = ""; - Inside the while loop, after the hello: print the prompt
what do you do?and read the job intooccupation. - Print a comment such as
occupation + " is such an interesting job!". - Keep the last two lines of the loop (ask for a name, update
name). Compile, run, test with two people, then bye.
String occupation = "";
...
System.out.print("what do you do? ");
occupation = myInput.nextLine();
System.out.println(occupation + " is such an interesting job!");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.
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.
- In QueenBot, replace the single comment line with a
switch (occupation). - Add
case "queen":andcase "student":with their own replies, each ending inbreak;. - Add
default:with the general reply. - Compile and test with
student,queenandchef.
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!");
}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.
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.
- Open Ex_EstateAgent_To_HouseTour and read the old EstateAgent code in the comment block.
- Right-click ScannerTemplate → Duplicate... → name it
HouseTour. Fix the class name and thenew ...().run()line if needed. - Inside
run(), after the Scanner line: printWhich room would you like to see (bye to exit)?and readString room = myInput.next(); - Write
while (!room.equals("bye")) { ... }. - Inside the loop, copy the room comments (the if / else if / else chain) from EstateAgent.
- 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.
String[] rooms = {"hall", "kitchen"};
for (String room : rooms) {
System.out.println(room);
}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 { }.
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?");
}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="")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)
- Change the if / else if / else chain in HouseTour to a
switch (room). - One
caseper room, each ending inbreak;. Usedefault:for any other room. - Compile and test with the same rooms as before. The output should not change.
switch (room) {
case "kitchen":
System.out.print("Can you smell the coffee? ");
break;
default:
System.out.print("What is this room used for?");
}match room:
case "kitchen":
print("Can you smell the coffee? ", end="")
case _:
print("What is this room used for?", end="")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.
- Open Ex_DrawSquare. The StarRating code from last week is copied in the comment block.
- Click New Class..., name it
DrawSquare, choose Class, OK. Open it, delete everything, and paste the StarRating code from the comment. RenameStarRatingtoDrawSquarein both places. - Read the size with
int stars = myInput.nextInt();(you will need the Scanner import and line from ScannerTemplate). - Make a counter
int line = 0;and a loopwhile (line < stars) { ... line++; }around the switch. - Test with 3 and 5. Then try 7. What goes wrong?
- Fix it: swap the switch for a second while loop inside the first one, with its own counter
x.
int stars = myInput.nextInt();
int line = 0;
while (line < stars) {
int x = 0;
while (x < stars) {
System.out.print("*");
x++;
}
System.out.println();
line++;
}stars = int(input("How many stars? "))
line = 0
while line < stars:
x = 0
while x < stars:
print("*", end="")
x += 1
print()
line += 1nextInt() reads a whole number, so you can compare it with <. A loop inside a loop needs different loop variables (line and x).
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
- Only now, open Sol1_QueenBot and Sol2_QueenBot. Compare with yours.
- Open Sol1_HouseTour_WhileIfElse and Sol2_HouseTour_WhileSwitch.
- If you tried DrawSquare: open Sol1_DrawSquare_WhileSwitch and Sol2_DrawSquare_2Whiles.
- Run each model answer once. Note one thing that is different from yours.
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).
- Duplicate HelloEverybody and call it
SpecialNames. - 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.
- Test with Tom, Harry, Ann, bye.
.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).
- Duplicate ScannerTemplate as
Santa1. Ask how many Ho!s, read it withnextInt(), then count it down in a while loop. - Then make
Santa2: keep asking until the user types 0 or a negative number. Use two while loops.
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
- Open Ex_CityRatings_Challenging and read the instructions in the comment at the top.
- Use the enhanced for loop over
cities. For each city ask “Have you visited ...? (yes/no)”. - 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!”.
- Then compare with Sol1, Sol2 and Sol3_CityRatings. Each one explains at the top what it does differently.
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.
You are done when
- QueenBot runs: you type
Ann,teacher,Ben,student,byeand it greets both people, comments on both jobs, and then stops. - HouseTour runs:
kitchengives “Can you smell the coffee?”,atticgives “What is this room used for?”, andbyeends 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
4prints 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.