Get the App
SLTechnology News&Howtos  ›  Development  › 

How to guess numbers by Java

Shulou Source: shulou.com Published: 2022-06-01 02:56:42 09月20日 Update

This article will explain in detail how to guess numbers in Java. The editor thinks it is very practical, so I share it for you as a reference. I hope you can get something after reading this article.

Guess the number

Title:

The program automatically generates a number between 1 and 100, and the utility implementation guesses what the number is? When guessing wrong, give corresponding hints according to different situations:

The guessed number is larger than the real number, which suggests that the guessed data is larger.

The guessed number is smaller than the real number, which suggests that the guessed number is smaller.

The guessed number is equal to the real number, which means congratulations on your guess.

Analysis:

Generate the number using a random number (range 0-100)

Repeat the guessing process using a loop

Use the keyboard to input guessing numbers

Compare the guessed number with the generated number

End the cycle after a good guess

Practice:

The code is as follows (example):

Public class Demo2 {public static void main (String [] args) {/ / do not like ginger, not jealous / / use random numbers to generate the number (range 0-100); / / need guide package import java.util.Random; Random r=new Random (); int num=r.nextInt (100) + 1; / / use loop to guess numbers repeatedly While (true) {/ / use the keyboard to enter guessed numbers; Scanner sc = new Scanner (System.in); System.out.println ("Please enter your guessed numbers:"); int s = sc.nextInt (); / / compare the guessed numbers with the generated numbers If (s > num) {System.out.println ("guess a big number!") ;} else if (s

Tags: Numbers generation loops prompts guesses articles input utility more programs ranges procedures keyboards random numbers different good between code content situation Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Tech Info MySQL Docker Apple MariaDB