while
(Condition-based) Loopswhile (condition) loop body
{}
's)
for
loop is based on a count; while
loop on a condition
for
loop is thus often called a counting loop
for (int i = m; i <= n; i++) … // loop bodyis (essentially) the same as:
int i = m; while (i <= n) { … // loop body i++; }
int num; while (num >= 0) { System.out.println("Enter a number (< 0 to end):"); num = scanner.nextInt(); // the rest of the loop body — processing 'num' }
num
nextInt
. However, that would
generate a compilation error as the loop header used the value of num
which must therefore
be declared earlier.
int num = 0;
while (num >= 0) {
System.out.println("Enter a number (< 0 to end):");
num = scanner.nextInt();
// the rest of the loop body — processing 'num'
}
-1
(i.e., the user wants to exit immediately without entering any numbers),
the correct behavior should be to do nothing (i.e., terminate the loop even before the
first iteration); however our code will have already entered the loop, prompted for and processed this first (negative) number
even though it's negative. It's only after going back to the top of the loop that we detect the fact the number was negative and
exit the loop, but by then its too late — the number has been processed already.
do while
loop form — a much less frequent loop construct than
the while
or for
, but one which ensure at least one pass through the loop body.
System.out.println("Enter a number (< 0 to end):");
num = scanner.nextInt();
while (num >= 0) {
// The loop body — here is where we process num
; note the placement of this code before the code to get the next set of values
System.out.println("Enter a number (< 0 to end):");
num = scanner.nextInt();
}
// This code in INCORRECT! System.out.println("Enter a number (< 0 to end):"); num = scanner.nextInt(); while (num >= 0) { System.out.println("Enter a number (< 0 to end):"); // this properly belongs at the bottom of the loop num = scanner.nextInt(); // the loop body — processing 'num' }
while
and for
loops available, we can present more general techniques for
reading files containing varying amounts of data.
for loop
(as we have a count of the number of values to read in)
import java.io.*; import java.util.*; public class HeaderValue { public static void main(String [] args) throws Exception { Scanner scanner = new Scanner(new File("numbers.text")); int howMany = scanner.nextInt(); for (int i = 1; i <= howMany; i++) { int number = scanner.nextInt(); System.out.println(number); } } }
while loop
(as we are looping on a condition —
i.e., read the data and process while it's not the trailer value)
****
is input, printing the words
as they are read in.
import java.io.*; import java.util.*; public class TrailerValue { public static void main(String [] args) throws Exception { Scanner scanner = new Scanner(new File("words.text")); String name = scanner.next(); // priming the pump while (!name.equals("****")) { System.out.println(name); name = scanner.next(); } } }
import java.util.*; public class TrailerValue { public static void main(String [] args) throws Exception { Scanner scanner = new Scanner(System.in); System.out.print("Enter a number (-1 to quit): "); // priming the punp int grade = scanner.nextInt(); // " while (grade >= 0) { System.out.println(grade); System.out.print("Enter a number (-1 to quit): "); grade = scanner.nextInt(); } } }
grade
is needed in the condition, we must prime the pump by getting its value
grade
(we're reading from the keyboard), so it too
is part of the priming logic
Scanner
class provides methods name hasNextxxx
(e.g., hasNext
,
hasNextInt
, etc), that parallel the nextxxx
methods, and return a boolean
(true if there is more data in the file or keyboard, and it is of the specified type).
while loop
(as we are looping on a condition — end of file not yet encountered)
import java.io.*; import java.util.*; public class EOF { public static void main(String [] args) throws Exception { Scanner scanner = new Scanner(new File("numbers.text")); while (scanner.hasNextInt()) { int number = scanner.nextInt(); System.out.println(number); } } }
scanner.nextInt
; i.e., the condition
contains no variables of ours that have to be initialized
scanner
takes care of itself and will be able to
respond correctly to our call
import java.io.*; import java.util.*; public class EOF { public static void main(String [] args) throws Exception { Scanner scanner = new Scanner(System.in); System.out.print("number? "); while (scanner.hasNextInt()) { int number = scanner.nextInt(); System.out.println(number); System.out.print("number? "); } } }
students.text
Weiss Gerald 1234 A 3212 B 0000 2023 Arnow David 5412 A 3523 C 6512 B 0000 2024 Sokol Dina 1234 B 0000 2025
hasNext
returns false).
hasNext
logic could be used; we will avoid that discussion for now
****
or 0000
(we assume the latter would not be used as a course code); we
choose the latter.
import java.io.*; import java.util.*; public class ProcessStudentData { public static void main(String [] args) throws IOException { final String CODE_TRAILER_VALUE = "0000"; Scanner scanner = new Scanner(new File("students.text")); while (scanner.hasNext()) { String last = scanner.next(); String first = scanner.next(); System.out.println(last + "," + first); String code = scanner.next(); while (!code.equals(CODE_TRAILER_VALUE)) { String grade = scanner.next(); System.out.println("\t" + code + ": " + grade); code = scanner.next(); } int gradYear = scanner.nextInt(); System.out.println("Graduating in " + gradYear); System.out.println(); } } }
Stdout
Weiss,Gerald 1234: A 3212: B Graduating in 2023 Arnow,David 5412: A 3523: C 6512: B Graduating in 2024 Sokol,Dina 1234: B Graduating in 2025
import java.util.*; public class GuessingGame { public static void main(String [] args) { Scanner scanner = new Scanner(System.in); final int theNumber = 4; System.out.println( "=== Pick a number game ==="); System.out.print("Enter a number from 1 to 10: "); int theGuess = scanner.nextInt(); while (theGuess != theNumber) { System.out.println( "Nyah yah nyah nyah nyah.... try again"); System.out.print("Enter a number from 1 to 10: "); theGuess = scanner.nextInt(); } System.out.println( "You got it right!"); } }
theGuess
which appears in the condition
Some of the more commonly-used packages;
io
contains classes for handling input/output (I/O): File
lang
contains classes dealing with language elements: String
, System
, Math
util
contains various 'useful' classes: Scanner
, Random
import java.util.*; public class GuessingGame { public static void main(String [] args) { Scanner scanner = new Scanner(System.in); Random random = new Random(); final int theNumber = random.nextInt(10) + 1; System.out.println( "Pick a number game"); System.out.print("Enter a number from 1 to 10: "); int theGuess = scanner.nextInt(); while (theGuess != theNumber) { System.out.println( "Nyah yah nyah nyah nyah.... try again"); System.out.print("Enter a number from 1 to 10: "); theGuess = scanner.nextInt(); } System.out.println( "You got it right!"); } }
public class MultiplicationTable { public static void main(String [] args) throws Exception { for (int i = 1; i <= 10; i++) { for (int j = 1; j <= 10; j++) System.out.print(i * j + " "); System.out.println(); } } }
Stdout
1 2 3 4 5 6 7 8 9 10 2 4 6 8 10 12 14 16 18 20 3 6 9 12 15 18 21 24 27 30 4 8 12 16 20 24 28 32 36 40 5 10 15 20 25 30 35 40 45 50 6 12 18 24 30 36 42 48 54 60 7 14 21 28 35 42 49 56 63 70 8 16 24 32 40 48 56 64 72 80 9 18 27 36 45 54 63 72 81 90 10 20 30 40 50 60 70 80 90 100
public class MultiplicationTable {
public static void main(String [] args) throws Exception {
for (int i = 1; i <= 10; i++) {
for (int j = 1; j <= 10; j++)
System.out.printf("%3d ", i * j);
System.out.println();
}
}
}
Stdout
1 2 3 4 5 6 7 8 9 10 2 4 6 8 10 12 14 16 18 20 3 6 9 12 15 18 21 24 27 30 4 8 12 16 20 24 28 32 36 40 5 10 15 20 25 30 35 40 45 50 6 12 18 24 30 36 42 48 54 60 7 14 21 28 35 42 49 56 63 70 8 16 24 32 40 48 56 64 72 80 9 18 27 36 45 54 63 72 81 90 10 20 30 40 50 60 70 80 90 100
printf
Methodprintf("format", args &hellip)
%[flags][width][.precision]conversionwhere:
public class MultiplicationTable {
public static void main(String [] args) throws Exception {
for (int i = 1; i <= 10; i++)
doOneRow(i);
}
public static void doOneRow(int i) {
for (int j = 1; j <= 10; j++)
System.out.printf("%3d ", i * j);
System.out.println();
}
}
nextLine
)last-name first-name course-codes … last-name first-name course-codes … …
import java.io.*;
import java.util.*;
public class LineScanner {
public static void main(String [] args) throws IOException {
Scanner fileScanner = new Scanner(new File("student.data"));
while (fileScanner.hasNextLine()) {
String line = fileScanner.nextLine();
Scanner lineScanner = new Scanner(line);
System.out.println(lineScanner.next()); // last name
System.out.println(lineScanner.next()); // first name
while (lineScanner.hasNextInt()) {
int courseCode = lineScanner.nextInt();
System.out.println(courseCode);
}
System.out.println();
}
}
}
do
/while
Loopdo
/while
loop — (again derived from C/C++), whose frequency of usage is far less than
either the for
loop or the while
loop. The basic syntax is:
do { loop body } while(condition);
do { play the game … … System.out.print("Want to play again? "); String response = scanner.next(); } while (response.equals("Yes"));