scannerWhile lab project. The transcript has no timestamps, so instead of times this page tells you the stage of the lecture (early, middle, near the end) where each point comes up.Key ideas, in lecture order
One idea per block, in the order the lecture covers them. Java code has a comment on every line. If you want to see how the same thing looks in Python, open the “Show me the Python version” boxes. They start closed.
Ideas: 1 · 2 · 3 · 4 · 5 · 6 · 7 · 8 · 9 · 10 · 11 · 12
1Quick recap of Week 1
The lecture started with a recap. Last week you met:
- the three basic structures: sequence, selection and repetition (loops);
- two ways to choose:
if/elseandswitch/case/break/default; - the enhanced
forloop, which runs its body once for each item in an array (a group of values of the same type, stored under one name); - variables: named boxes. Each box has a name and a type, and holds one value at a time.
run(). Semicolon ; ends each Java instruction. Compile: turn your Java into a form the computer can run (BlueJ’s Compile button). Terminal: BlueJ’s Terminal Window, where output appears and where you type input.Stage: the very start of the lecture.
2Input and output (IO)
Programs need to talk to the outside world. That is called input and output, or IO.
- Input: information coming into the program, for example from the keyboard, mouse, touch screen, a file or another program.
- Output: information the program sends out, for example to the screen, a file or another program.
Humans do IO too. Your senses are inputs; talking, moving and writing are outputs. In a conversation, my output is your input.
Java gives you two basic channels: System.out (output to the screen, which you used with System.out.println) and System.in (input from the keyboard).
Stage: early in the lecture.
3Scanner: reading what the user types
Scanner is a class that comes with Java. It makes reading keyboard input easy. Using it takes a few steps, all shown in SayHello:
// What this class does: asks for your name, then greets you by name.
// import tells Java we want to use the Scanner class, which lives in java.util
import java.util.Scanner;
public class SayHello {
public void run() {
// The prompt: print (not println) so you type on the same line
System.out.print("What is your name? ");
// Make a new Scanner that reads from the keyboard (System.in),
// and keep it in a variable called myInput
Scanner myInput = new Scanner(System.in);
// Wait for the user to type a word and press Enter.
// Store that word in a new String variable called name
String name = myInput.next();
// Greet the user, using the value stored in name
System.out.println("Hello " + name + ", nice to meet you");
// Close the Scanner because we have finished with it
myInput.close();
}
// Start the program (BlueJ: right-click, void main)
public static void main(String[] args) {
new SayHello().run();
}
}
import java.util.Scanner;goes at the very top. import tells Java to fetch a ready-made class from its library. Without it, Java does not know whatScanneris.- Print a prompt: a message that tells the user what to type. Use
print, so the typing appears on the same line. Scanner myInput = new Scanner(System.in);makes the Scanner.newcreates a new object (a working copy of a class). You can choose the variable name (myInput), but the rest must be exactly like this. The lecturer said: just remember this line for now; you will understand why later.myInput.next()calls a method on the Scanner. The dot means “use this method of that object”. The program stops and waits until the user types and presses Enter.myInput.close();at the end, when you have finished with it.
In BlueJ, the Terminal Window has an input line at the bottom. Type there and press Enter. While the program waits, BlueJ’s “running” bar stays striped: the program has not crashed, it is waiting for you.
Show me the Python version
name = input("What is your name? ") # prompt and read in one step
print("Hello " + name + ", nice to meet you")Python’s input() does the prompt and the reading in one go, and needs no import. Java needs the import, a Scanner object, a separate prompt, and a method call to read.
Stage: early to middle. The lecturer live-coded SayHello, starting from what the Terminal Window should look like.
4next, nextLine, nextInt, nextDouble
| Method | Reads | Gives you | Example |
|---|---|---|---|
next() | one word, up to a space or Enter | String | String word = myInput.next(); |
nextLine() | the whole line, spaces included | String | String line = myInput.nextLine(); |
nextInt() | a whole number | int | int age = myInput.nextInt(); |
nextDouble() | a decimal number | double | double price = myInput.nextDouble(); |
The lecturer’s demo: if you type New York, nextLine() gets "New York", but next() only gets "New". Also, next() always gives you a String: if you type 42, you get the text "42", not a number you can do sums with. Use nextInt() for that.
// What this class does: asks three questions and reads a line of text,
// a whole number and a decimal number.
import java.util.Scanner; // we need the Scanner class
public class AskThree {
public void run() {
// Make the Scanner that reads from the keyboard
Scanner myInput = new Scanner(System.in);
// Read a whole line, so "Tom Edwards" is kept in full
System.out.print("What is your full name? ");
String name = myInput.nextLine();
// Read a whole number into an int box
System.out.print("How old are you? ");
int age = myInput.nextInt();
// Read a decimal number into a double box
System.out.print("What did lunch cost? ");
double price = myInput.nextDouble();
// Use all three values
System.out.println(name + " is " + age + " and spent " + price);
// Finished with the Scanner
myInput.close();
}
// Start the program
public static void main(String[] args) {
new AskThree().run();
}
}Show me the Python version
name = input("What is your full name? ") # always a string
age = int(input("How old are you? ")) # turn the text into a whole number
price = float(input("What did lunch cost? ")) # turn the text into a decimal
print(name, "is", age, "and spent", price)Python’s input() always gives text, like nextLine(). Python’s int(input()) is like nextInt(), and float(input()) is like nextDouble().
nextFloat(), nextLong(), nextBoolean() and others as a cheat sheet. The lecturer said you can ignore those for now.Stage: the middle of the lecture, after SayHello.
5ScannerTemplate and Duplicate
The lab project has a class called ScannerTemplate. It holds just the basic Scanner code: the import, making the Scanner, and closing it. To start a new program that needs input, right-click ScannerTemplate in BlueJ, choose Duplicate…, give the copy a name that starts with a capital letter, and add your code in the middle.
6TripAdvisor: Scanner plus switch
TripAdvisor brings back last week’s StarRating. Instead of ratings fixed in an array, it asks the user for a place and a star rating, then uses a switch with fall-through (no break between cases) to print that many stars.
// What this class does: asks where you went and how many stars (1-5)
// you give it, then prints the place and that many stars.
import java.util.Scanner; // we need the Scanner class
public class TripAdvisor {
public void run() {
// Prompt for the place
System.out.print("Where have you just visited? ");
// Make the Scanner that reads from the keyboard
Scanner myInput = new Scanner(System.in);
// Read one word for the place
String place = myInput.next();
// Prompt for the rating, then read it. next() gives text, e.g. "3"
System.out.print("How many stars would you give it (1-5)? ");
String starNumber = myInput.next();
// Show the place and the rating, staying on the same line
System.out.print(place + " (" + starNumber + " stars): ");
// Choice with fall-through: jump to the matching case, then keep going
// down, printing one star per case. default 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:
System.out.println("");
}
// Finished with the Scanner
myInput.close();
}
// Start the program
public static void main(String[] args) {
new TripAdvisor().run();
}
}The lab file uses ★ stars; this copy uses *. Because starNumber is a String, the case labels are in quotes: case "5":. In the live demo the lecturer read the rating as a whole number with nextInt() instead; then the labels would be case 5: with no quotes.
Stage: the middle of the lecture, just before the break.
7The while loop
The enhanced for loop needs an array: it runs once per item. A while loop needs no list. It uses a condition (a test that is true or false), like an if statement.
The pattern is while (condition) { body }. Read it as: “while the condition is true, run the body again”. Java checks the condition before each run of the body. When the condition is false, the loop stops and Java carries on after the closing }. If it is false the very first time, the body never runs at all.
// The loop variable: a counter that starts at 0
int x = 0;
// Loop: keep running the body while x is less than 5.
// x goes 0, 1, 2, 3, 4, so the body runs 5 times. When x is 5 the test is false and it stops.
while (x < 5) {
// Say Ho! and stay on the same line
System.out.print("Ho! ");
// Add 1 to x, so the loop moves towards stopping
x = x + 1;
}
// After the loop: finish the line
System.out.println();Show me the Python version
x = 0
while x < 5: # same test, no round brackets needed
print("Ho! ", end="")
x = x + 1
print()Python’s while works the same way. Java needs round brackets round the condition and curly brackets round the body.
if for while.Stage: right after the mid-lecture break.
8Making sure the loop stops
The condition’s code stays the same each time, but the values it checks can change. That is what lets a loop stop.
x or name. The loop body must change it, so that the condition can become false one day.There are two common ways to update the loop variable:
- User input: ask the user for a new value inside the loop (HelloEverybody).
- A calculation: add or subtract from a counter (Santa).
Stopping a runaway program in BlueJ: right-click the striped “running” bar at the bottom left of the main BlueJ window and choose Reset Java Virtual Machine. Then fix the loop and compile again.
9HelloEverybody: stopping with user input
// What this class does: keeps asking for names and greeting each one,
// until the user types bye.
import java.util.Scanner; // we need the Scanner class
public class HelloEverybody {
public void run() {
// First prompt, before the loop
System.out.print("What is your name (bye to exit)? ");
// Make the Scanner and read the first name (a whole line)
Scanner myInput = new Scanner(System.in);
String name = myInput.nextLine();
// Loop: keep going while name is NOT "bye".
// ! means "not". It stops as soon as the user types bye.
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)? ");
// ...and UPDATE the loop variable. Without this line it never stops
name = myInput.nextLine();
}
// Runs once the loop has stopped
System.out.println("Goodbye!");
// Finished with the Scanner
myInput.close();
}
// Start the program
public static void main(String[] args) {
new HelloEverybody().run();
}
}
! means not. name.equals("bye") is true when the name is bye, so !name.equals("bye") is true while the name is not bye. (The lab version has no “Goodbye!” line; the lecturer added a goodbye message in the live demo.)
Show me the Python version
name = input("What is your name (bye to exit)? ")
while name != "bye": # Java: !name.equals("bye")
print("Hello " + name + ", nice to meet you")
name = input("What is your name (bye to exit)? ")
print("Goodbye!")Python writes “not equal” as != and can compare text directly. Java uses ! in front of .equals() for Strings.
Stage: after the break. The lecturer first left out the update line, and the program printed “Hi Tom” forever until it was stopped.
10Santa: stopping with a calculation
// What this class does: Santa says Ho! five times on one line.
public class Santa {
public void run() {
// The loop variable: how many Ho!s are left to say
int x = 5;
// Loop: repeat while x is greater than 0.
// x goes 5, 4, 3, 2, 1, so 5 Ho!s. When x reaches 0 it stops.
while (x > 0) {
// Say Ho! and stay on the same line
System.out.print("Ho! ");
// Take 1 away from x so the loop can stop
x = x - 1;
}
// After the loop: move to a new line
System.out.println();
}
// Start the program
public static void main(String[] args) {
new Santa().run();
}
}
x = x - 1; looks like a maths equation, but it is an instruction: “take the value in x, subtract 1, and store the result back in x”. Java reads the right-hand side first.
Shortcuts: x++ adds 1 (increment) and x-- subtracts 1 (decrement). x++; does the same as x = x + 1;. The lecturer used the long form in class because it is easier to read when you start.
Show me the Python version
x = 5
while x > 0:
print("Ho! ", end="")
x = x - 1 # or x -= 1. Python has no x-- or x++
print()Python has x -= 1 and x += 1, but not x-- or x++. Java has all of them.
Stage: after HelloEverybody. In the live demo the lecturer counted up from 0 with x < 5 (the version in idea 7); the lab file counts down from 5.
11Predictable and unpredictable loops
- Input-based loops are unpredictable: they depend on what the user types.
- Calculation-based loops are predictable: they run the same way every time.
- General rule: code is predictable unless it uses something from outside, like user input. You can mix the two: a counting loop that runs as many times as the user asks (see the DrawSquare exercise). Java also has random numbers, which add unpredictability even without input.
12Optional: a loop inside a loop
The “Tell Santa” challenge uses two while loops, one inside the other. The outer loop keeps asking the user for a number until they type 0. The inner loop counts that many Ho!s. The inner loop finishes completely each time before the outer loop carries on.
// What this class does: asks how many Ho!s Santa should say, says them,
// and keeps asking until the user types 0.
import java.util.Scanner; // we need the Scanner class
public class Santa2 {
public void run() {
// Prompt, make the Scanner, read the first number
System.out.print("How many Hos do you want Santa to say (0 exit)? ");
Scanner myInput = new Scanner(System.in);
int number = myInput.nextInt();
// OUTER loop: keep going while the user has not typed 0.
// Its loop variable (number) is updated by user input at the end.
while (number != 0) {
// INNER loop: say Ho! and count number down to 0.
// Its loop variable is updated by a calculation.
while (number > 0) {
System.out.print("Ho! ");
number = number - 1;
}
// Move to a new line, then ask again (this updates the outer loop variable)
System.out.println("");
System.out.print("How many Hos do you want Santa to say (0 exit)? ");
number = myInput.nextInt();
}
// Finished with the Scanner
myInput.close();
}
// Start the program
public static void main(String[] args) {
new Santa2().run();
}
}Show me the Python version
number = int(input("How many Hos do you want Santa to say (0 exit)? "))
while number != 0: # outer loop: until the user types 0
while number > 0: # inner loop: count down
print("Ho! ", end="")
number = number - 1
print()
number = int(input("How many Hos do you want Santa to say (0 exit)? "))Same shape in Python: the inner loop is indented one more level. In Java, each loop has its own pair of curly brackets.
Stage: near the end of the lecture.
What the lecturer stressed
These points come from the 2026 Week 2 transcript. It has no timestamps, so each point is labelled with the stage of the lecture where it comes up. Points labelled “Slides” are tips printed on the slides.
- StartWhen you see a variable name in code, think of the value inside it. In the recap, the lecturer stressed that printing
xprints the value in the x box, not the letter x. Text in speech marks is a fixed String. - EarlyWithout input, a program always does the same thing. Input lets the user take part while the program is running.
- Early to middleDesign from the Terminal Window. The lecturer built SayHello by first picturing what the user should see (“What is your name?”), then writing the code to match.
- Early to middleA waiting program has not crashed. When the program reaches a Scanner read, it stops and waits for you to type in the Terminal Window and press Enter. BlueJ’s running bar shows it is still going.
- Early to middleLearn the Scanner line by heart for now.
Scanner myInput = new Scanner(System.in);You can choose the name (myInput), and you must saynew. You will understand why it is written this way later. - Early to middleImport, then close. The code gave an error until
import java.util.Scanner;was added: built-in classes like Scanner usually need an import. Close the Scanner when you have finished with it. - Middlenext() versus nextLine(). Typing “Tom Edwards” or “New York”:
nextLine()keeps the whole thing,next()only keeps the first word. UsenextInt()for whole numbers andnextDouble()for decimals. The lecturer suggested trying the difference yourself. - Middle and near the endMake your program user-friendly. Always print a prompt first, otherwise the user sees an empty Terminal Window and does not know what to type. Tell them how to exit, for example “(0 to exit)”.
- After the breakBuild the structure first. Type
while ( ) { }with both brackets, then fill in the condition and the body. Otherwise you forget a closing bracket and spend ages looking for it. - After the breakUpdate the loop variable inside the loop. The lecturer ran HelloEverybody without the update line on purpose. It greeted Tom again and again, forever, and had to be stopped from BlueJ. Give the user a chance to type a new value, usually at the end of the loop body.
- After the breakCounters usually start at 0 in computing. Starting at 0 with
x < 5runs the body 5 times (0, 1, 2, 3, 4). Be careful at the edges: changing the start value or using<=changes how many times it runs. - After the break
x = x + 1is an instruction, not an equation. Java works out the right-hand side first, then stores it back in x.x++is the same thing; the lecturer used the long form because it is easier for beginners. - Near the endNested loops take time. In the “Tell Santa” challenge the inner loop finishes completely before the outer loop asks again. Understand a single loop first, and don’t worry if this feels hard.
- Always check that your loop has a way to stop before you run it.
- Lab tips. DrawSquare is an extension, so don’t worry if you cannot do it. Only open the
Solclasses after you have tried the exercise yourself. Some exercises have several solutions (for example Sol1_QueenBot and Sol2_QueenBot).
Nothing in this lecture said anything specific about the coursework.
Flashcards
Read the question. Say your answer out loud or in your head. Then click the card to flip it. Be honest: click I know it or Don’t know yet. Your marks are saved in this browser, so you can come back later.
“Only the ones I don’t know” hides every card you have marked I know it. Cards you have not marked yet stay in, so nothing gets skipped.
Quiz
15 questions: multiple choice, “what will this print?” and “spot the bug”. Click an answer. You find out straight away if it is right, with a short explanation. Your answers and your score are saved in this browser.
Common mistakes
These are the slips beginners make most often with this week’s topics. The “wrong” code is shown in red; do not copy it.
Forgetting the import
Without import java.util.Scanner; at the top, the compiler says it cannot find Scanner.
public class AskName {// The import goes on the very first lines, before the class
import java.util.Scanner;
public class AskName {Using next() when you want the whole line
next() stops at the first space. For names like Tom Edwards or places like New York, use nextLine().
String place = myInput.next(); // gets only "New"
// nextLine keeps the whole line, spaces included String place = myInput.nextLine();
Putting next() into an int box
next() gives text. Use nextInt() for whole numbers and nextDouble() for decimals.
int age = myInput.next();
// nextInt reads a whole number int age = myInput.nextInt();
Forgetting to update the loop variable
If nothing in the body changes the loop variable, the loop runs forever. Update it at the end of the body.
while (!name.equals("bye")) {
System.out.println("Hello " + name);
}// Loop: greet, then read a new name so the loop can stop at "bye"
while (!name.equals("bye")) {
System.out.println("Hello " + name);
name = myInput.nextLine(); // update the loop variable
}Changing the counter the wrong way
Counting up towards a limit needs + 1. Counting down towards 0 needs - 1. Check the direction matches the condition.
while (x < 5) {
x = x - 1;
}// Loop: x moves up towards 5, so the test can become false
while (x < 5) {
x = x + 1;
}Off by one
Starting at 0 with x < 5 runs 5 times. Starting at 0 with x <= 5 runs 6 times. Trace the first and last values by hand.
Using == or != to compare Strings
For text, use .equals(), and ! in front for "not equal". != is fine for numbers, like number != 0.
while (name != "bye") {
name = myInput.nextLine();
}// ! in front of .equals means "not equal" for text
while (!name.equals("bye")) {
name = myInput.nextLine();
}No prompt
If you read input without printing a prompt first, the user sees an empty Terminal Window and does not know what to type.
Mixing nextInt() and nextLine()
nextInt() reads the number but leaves the Enter behind. A nextLine() straight after it then gets an empty line. If you need text after a number, add an extra myInput.nextLine(); first to use up that Enter, or read the text before the number.
Semicolon after the while condition
while (x < 5); with a semicolon ends the loop right there, with an empty body, so the real body never repeats (and the loop may never stop). No semicolon before the {.
Python habits
x++ exists in Java but not in Python. Java needs ( ) round the condition and { } round the body; there is no colon.
The recording
Watch the 2026 Week 2 lecture recording (Panopto; sign in with your University of Brighton account).
No timestamps were available, so use the stage labels in “What the lecturer stressed” as a rough guide: IO and Scanner come in the first half, the break comes after TripAdvisor, and while loops (HelloEverybody, Santa, then the nested-loop challenge) fill the second half.
Files: Week 2 Sunday Prep · Week 2 Lab Walkthrough · lecture slides (.pptx) · lab project scannerWhile.zip
How this pack was made
This pack was made from:
- The Week 2 slides Input and Repetition - Scanner + While Loop, including the lab instructions at the end and the slide notes (which hold the “Tell Santa” challenge code).
- The Week 2 lab project
scannerWhile.zip(ScannerTemplate, SayHello, TripAdvisor, HelloEverybody, Santa and the exercises). - The full auto-generated English transcript of the 2026 Week 2 recording (about 7,300 words). It has no timestamps, so points are placed by lecture stage. Auto-captions garble code words (Scanner, nextInt and so on); these were read against the slides, and nothing garbled is quoted as the lecturer’s words.
Every Java example that is meant to be correct was compiled with the Java compiler (javac). The “what will this print?” answers were checked by running the code.