Joseph Haugh
University of New Mexico
boolean isPositive(int n) {
return n >= 0;
}
int validateUserInput() {
String input = IO.readln("Enter a positive number: ");
int n = Integer.parseInt(input);
while (!isPositive(n)) {
input = IO.readln("Enter a positive number: ");
n = Integer.parseInt(input);
}
return n;
}
void main() {
int n = validateUserInput();
IO.println(n);
}
boolean isPositive(int n) {
return n >= 0;
}
int validateUserInput() {
String input = IO.readln("Enter a positive number: ");
int n = Integer.parseInt(input);
while (!isPositive(n)) {
input = IO.readln("Enter a positive number: ");
n = Integer.parseInt(input);
}
return n;
}
void main() {
int n = validateUserInput();
IO.println(n);
}
Do while has the following syntax:
do {
<<bodyStatements>>
} while (<<booleanCondition>>);Do while is useful when you need the body of the loop to run first then check the condition
This is exactly what we need for our example!
boolean isPositive(int n) {
return n >= 0;
}
int validateUserInput() {
String input; // Is this necessary?
int n; // Or this? Why?
do {
input = IO.readln("Enter a positive number: ");
n = Integer.parseInt(input);
} while (!isPositive(n));
return n;
}
void main() {
int n = validateUserInput();
IO.println(n);
}
int validateUserInput() {
do {
// We could put input inside the loop without
// error, but it would be suboptimal
String input = IO.readln("Enter a positive number: ");
int n = Integer.parseInt(input);
} // n is out of scope after this curly brace
// Thus, it cannot be seen in this condition!
while (!isPositive(n));
// Can also not be seen here!
return n;
}
// Or here for that matter!
Many loops take on the following form:
<<initStatements>>
while (<<booleanCondition>>) {
<<bodyStatements>>
<<updateStatements>>
}For example, this loop we saw a few days ago has this form:
int result = 0; // Init statement
int i = 1; // Init statement
while (i <= n) {
result += i; // Body statement
i++; // Update statement
}This pattern is so common there is a dedicated loop construct for it
Its called a for loop
Caution:
For loop syntax:
for (<<initStatement>>; <<booleanCondition>>; <<updateStatement>>) {
<<bodyStatements>>
}For example our previous while loop example:
int result = 0; // Init statement
int i = 1; // Init statement
while (i <= n) {
result += i; // Body statement
i++; // Update statement
}Could be rewritten with a for loop:
int result = 0;
for (int i = 1; i <= n; i++) {
result += i;
}