Explore the English language on a new scale using AI-powered English language navigator.
Number guessing game code snippetAbstractJava program playing number guessing game. Rules are:
Source codeNumberGuessingGame.javaimport java.util.Scanner;
public class NumberGuessingGame { public static void main(String[] args) { int secretNumber; secretNumber = (int) (Math.random() * 999 + 1); Scanner keyboard = new Scanner(System.in); int guess; do { System.out.print("Enter a guess (1-1000): "); guess = keyboard.nextInt(); if (guess == secretNumber) System.out.println("Your guess is correct. Congratulations!"); else if (guess < secretNumber) System.out .println("Your guess is smaller than the secret number."); else if (guess > secretNumber) System.out .println("Your guess is greater than the secret number."); } while (guess != secretNumber); } } Download NumberGuessingGame.java Sample runEnter a guess (1-1000): 500 Your guess is greater than the secret number. Enter a guess (1-1000): 250 Your guess is greater than the secret number. Enter a guess (1-1000): 125 Your guess is greater than the secret number. Enter a guess (1-1000): 62 Your guess is greater than the secret number. Enter a guess (1-1000): 31 Your guess is smaller than the secret number. Enter a guess (1-1000): 50 Your guess is greater than the secret number. Enter a guess (1-1000): 40 Your guess is correct. Congratulations!
ExtraCheck for practice lesson, explaining development of number guessing game step by step: Practice. Developing "number guessing game" step by step. |