Homework Units 4

  • Unit 4 CB Homework NONE
import java.util.Scanner;
 
public class GFG {
 
    // Function that implements the
    // number guessing game
    public static void
    guessingNumberGame()
    {
        // Scanner Class
        Scanner sc = new Scanner(System.in);
 
        // Generate the numbers
        int number = 1 + (int)(100
                               * Math.random());
 
        // Given K trials
        int K = 5;
 
        int i, guess;
 
        System.out.println(
            "A number is chosen"
            + " between 1 to 100."
            + "Guess the number");
 
        // Iterate over K Trials
        for (i = 0; i < K; i++) {
 
            System.out.println(
                "Guess the number:");
 
            // Take input for guessing
            guess = sc.nextInt();
 
            if (number == guess) {
                System.out.println(
                    "You guessed the number");
                break;
            }
            else if (number > guess
                     && i != K - 1) {
                System.out.println(
                    "Wrong number"  + guess);
            }
            else if (number < guess
                     && i != K - 1) {
                System.out.println(
                    "Wrong number" + guess);
            }
        }

    }
 
    // Driver Code
    public static void
    main(String arg[])
    {
 
        // Function Call
        guessingNumberGame();
    }
}
GFG.main(null);
A number is chosen between 1 to 100.Guess the number within 5 trials.
Guess the number:
Wrong number36
Guess the number:
Wrong number36
Guess the number:
Wrong number36
Guess the number:
Wrong number36
Guess the number: