CSE 121
CSE 121
  • Home / Calendar
  • Syllabus
  • Assignments
  • Resubmissions
  • Exam
  • Course Staff
  • Office Hours
  • Grading Rubrics
  • Resources

  • Course Tools
  • EdStem
  • Anonymous Feedback
  • Acknowledgements

While Loops, User Input, and Scanner


24au ver.

Note: this is for the Autumn 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
}

Search

Search the class website; related sections and pages will appear below. Note: this search is not as forgiving with typos as other search engines.