Notes

  • While loops run when conditional is true
  • For loops defines a variable that changes every loop and runs when the conditional is true
  • Nested iteration can be good in situations
  • Enhanced for loops can loop through all elements in an array but the array cannot be modified when it is looping

Homework

Part 1

  1. Write a program where a random number is generated. Then the user tries to guess the number. If they guess too high display something to let them know, and same for if they guess a number that is too low. The loop must iterate until the number is guessed correctly.
import java.lang.Math;
import java.util.Scanner;

public class NumberGuess {
    private int answer;
    private int guess;
    Scanner in = new Scanner(System.in);
    public NumberGuess() {
        this.answer = (int) Math.floor(Math.random()*10 + 1);
        System.out.println(answer);
    }
    public void play() {
        while (answer != guess) {
            this.getGuess();
        }
        in.close();
    }
    public void getGuess() {
        System.out.print("Guess a number 1-10: ");
        this.guess = in.nextInt();
        System.out.println(this.guess);
        if (this.guess > this.answer) {
            System.out.println("too high");
        } else if (this.guess < this.answer) {
            System.out.println("too low");
        } else {
            System.out.println("congrats");
        }
    }
    public static void main(String[] args) {
        NumberGuess num = new NumberGuess();
        num.play();
    }
}
9
Guess a number 1-10: 9
congrats

Part 2

completed

completed