Unit 4 Iterations
student led lesson notes + homework
import java.util.Scanner;
public class Checker
{
public static void main(String[] args)
{
int number;
// Create a Scanner object for keyboard input.
Scanner keyboard = new Scanner(System.in);
// Get a number from the user.
System.out.print("Enter a number in the range of 1 through 100: ");
number = keyboard.nextInt();
while (number < 1 || number > 100)
{
System.out.print("Invalid input. Enter a number in the range " +
"of 1 through 100: ");
number = keyboard.nextInt();
}
}
}
Checker.main(null)
public class LoopConversion
{
public static void main(String[] args)
{
int count = 0;
//convert to for loop
for (count=0; count<5; count++)
{
System.out.println("count is " + count);
}
}
}
LoopConversion.main(null)
public class ForLoop
{
public static void main(String[] args)
{
int i = 0;
//convert to for loop
for (i=0; i<5; i++)
{
System.out.println(i);
}
}
}
ForLoop.main(null)
public class WhileLoop
{
public static void main(String[] args)
{
int i = 0;
//convert to for loop
while (i<5)
{
System.out.println(i);
i++;
}
}
}
WhileLoop.main(null)
import java.util.Scanner;
public class NumberGuesser { // creation of a class, capitalize internal words
public static void
guessnumber()
{
Scanner scanner = new Scanner(System.in);
int number = 1 + (int)(100* Math.random()); // use of random number generator using math class
int i, guess;
System.out.println(
"A number is chosen between 1 to 100."
+ "Guess the number"
+ " within 5 trials.");
for (i = 0; i < 5; i++) {
System.out.println(
"Guess a number:");
guess = scanner.nextInt();
if (number == guess) {
System.out.println("You guessed the number.");
break;
}
else if (number > guess&& i != 5 - 1) {
System.out.println("The number is greater than " + guess);
}
else if (number < guess && i != 5 - 1) {
System.out.println("The number is less than " + guess);
}
}
if (i == 5) {
System.out.println(
"You have used all 5 trials.");
System.out.println(
"The number was " + number);
}
}
// Driver Code
public static void
main(String arg[])
{
// Function Call
guessnumber();
}
}
NumberGuesser.main(null);