Part #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.

// Java utility imports necessary for the program
import java.util.Scanner;
import java.util.Random;

public class Iteration {
    // Initialize Random library object
    Random randNumber = new Random();
    int randomNumber = randNumber.nextInt(100 - 1) + 1;
    // Initialize Scanner object
    Scanner userInput = new Scanner(System.in);

    // Startup method
    public void play() {
        System.out.println("Guess an integer from 1 to 100");
        int guess = userInput.nextInt();
        System.out.println(guess);
        // Calls checkGuess method that checks if the guess matches the randomly generated number from 1-100
        checkGuess(guess);
    }

    // Simulates binary search random number guessing game. This essentially a recursive method that keeps running until the randomly generated number is guessed correctly
    public void checkGuess(int guess) {
        // Win condition
        if (guess == randomNumber) {
            System.out.println("Congratulations, you guessed correctly!");
        } 
        // Condition when guess is less than randomNumber
        else if (guess < randomNumber) {
            System.out.println("Too low");
            System.out.println("Guess again");
            int guess2 = userInput.nextInt();
            System.out.println(guess2);
            checkGuess(guess2);
        } 
        // Condition when guess is greater than randomNumber
        else if (guess > randomNumber) {
            System.out.println("Too high");
            System.out.println("Guess again");
            int guess2 = userInput.nextInt();
            System.out.println(guess2);
            checkGuess(guess2);
        }
    }
}

// Running method for visualizing outputs
public class runProgram {
    public static void main(String[] args) {
        Iteration myObj = new Iteration();
        myObj.play();
    }
}

runProgram.main(null);
Guess an integer from 1 to 100
50
Too high
Guess again
25
Too low
Guess again
37
Congratulations, you guessed correctly!

Part #2:

image