Java random number application-guessing game

Source: Internet
Author: User

I first contact Java, the understanding of Java is not comprehensive enough, now can only use the basic knowledge of Java to do a small programming game-guessing game!

The game is a rule: set a randomly generated secret value between 1-100, and then enter a value you guessed, if the number of guesses than the secret value, then use the input value instead of the larger value of the range, if the number of guesses than the secret value is smaller, then the input value instead of the smaller value of the range, so loop , you can exit the loop until the number of guesses equals the secret value. This game uses the knowledge of circular structure statements and random numbers.

Import Java.util.Random;

Import Java.util.Scanner;


public class Geuss_game {


public static void Main (string[] args) {

Scanner sc=new Scanner (system.in);

Random ran=new random ();

Double r=ran.nextdouble ();

int num= (int) (r*98) +2;//randomly generates a secret value

int small=1,big=100;//Sets the range variable, which varies according to the value entered

int input;//The value of the input is the number of guesses


for (;;) {//Unconditional loop

System.out.println ("Please enter a number between" +small+ "~" +big+ ":");

Input=sc.nextint ();

if (input>num) {//input value is greater than secret value, assign the input value to a larger value

Big=input;

}else if (input<num) {//input value is less than secret value, assigning the input value to a relatively small value

Small=input;

}else if (input==num) {//input value equals secret value, then jump out of loop

System.out.println ("Congratulations on your winning, please get ready for the show!!! ");

Break

}else{

SYSTEM.OUT.PRINTLN ("You entered the wrong range, please re-enter!") ");

Continue

}


}


}


Java random number application-guessing game

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.