CSE 121
CSE 121
  • Home / Calendar
  • Syllabus
  • Assignments
  • Resubmissions
  • Exam
  • Getting Help
  • Course Staff
  • Grading Rubrics
  • Resources

  • Course Tools
  • EdStem
  • Grade Calculator
  • Anonymous Feedback
  • Acknowledgements

While Loops, User Input, and Scanner


While Loops¶

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

While Loop Syntax

while (condition) {
    statement;
    ...
}

While Loop Example

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

While Loop 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 exception if not
nextDouble() one token as double (if possible) throws exception if not

Scanner 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)

java:Fenceposting with While Loops ExampleLh3 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.