24su ver.

Note: this is for the Summer 2024 iteration of CSE 121. Looking for a different quarter? Please visit https://courses.cs.washington.edu/courses/cse121/.

While Loops

(indefinite loop, we don’t know in advance how many times it will repeat!)

Syntax

while (condition) {
    statement;
    ...
}

Example

int num = 5;
while (num < 50) {
    num *= 5;
}
System.out.println(num);

Output

125

User Input and Scanner

(execute some behavior based on information the user gives us directly)

Scanner Methods

Method Description
next() one token as String
nextLine() entire line as String
nextInt() one token as int (if possible) throws execption if not
nextDouble() one token as double (if possible) throws exception if not

Example

import java.util.*; // make sure you don't forget this!

public class ScannerExample {
    public static void main(String[] args) {
        //Create a Scanner object
        Scanner console = new Scanner(System.in);
        // Get next integer user input from console and stores in num
        int num = console.nextInt();
    }
}

Fenceposting

(pulling one iteration out of the loop)

Example

int num = 1;
System.out.print(num); // one number to start with
while (num < 5) {
    num++;
    System.out.print(", " + num); // commas between numbers
}