Java if statement guess random number once

Question

We would like to guess a random number.

Prompt the user to enter a guess only once.

Guess the number once. Exit program after checking the guess.

Display the following:

  • Yes, the number is
  • Your guess is too high
  • Your guess is too low

import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    // Generate a random number to be guessed
    int number = (int)(Math.random() * 101);

    Scanner input = new Scanner(System.in);
    System.out.println("Guess a magic number between 0 and 100");

    //your code // w  ww  .ja  va 2 s  . co m
  }
}




import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    // Generate a random number to be guessed
    int number = (int)(Math.random() * 101);

    Scanner input = new Scanner(System.in);
    System.out.println("Guess a magic number between 0 and 100");

    // Prompt the user to guess the number
    System.out.print("\nEnter your guess: ");
    int guess = input.nextInt();
      
    if (guess == number)
      System.out.println("Yes, the number is " + number);
    else if (guess > number)
      System.out.println("Your guess is too high");
    else 
      System.out.println("Your guess is too low");    
  }
}



PreviousNext

Related