<> introduce

In many cases , Can encounter a small game of guessing numbers , Let's write one today Java Version of guessing numbers games .
thinking ：

* First, you need to generate a random number , And can no longer change , use Random of nextInt() method ;
* Keyboard input required , So you need to use Scanner;
* Gets the number entered by the keyboard , use Scanner of nextInt() method ;
* Two numbers have been obtained , Random numbers and keyboard numbers , We need to judge ：
* If the number entered is too large , The prompt is too large , And try again
* If the number entered is too small , The prompt is too small , And try again
* If you guessed right , game over !
* To try again is to try again , The number of cycles is uncertain , use ```while(true)```
Effect achieved ：

Until you guess right , Code to stop the loop
package com.itwcn.demo06; /** * @program: Demo04Random * @description: *
@author: OriginalCoder * @createtime:2020/10/28 22:57 **/ import java.util.
Random; import java.util.Scanner; public class Demo04Random { public static void
main(String[] args) { Random r = new Random(); int randomNum = r.nextInt(100) +
1; //[1,100]; If not +1, That's it 0-99 Scanner sc = new Scanner(System.in); while (true) {
System.out.println(" Please enter the number you guessed ："); int guessNum = sc.nextInt(); if(randomNum <
guessNum) { System.out.println(" It's too big ! Please try again "); } else if (randomNum > guessNum) {
System.out.println(" It's too small ! Please try again "); } else { System.out.println(" Guess right "); break;
// If you're right , Don't try again } } System.out.println(" You've tried too many times , game over "); } }
Guess right or over 10 second , Code to stop the loop
package com.itwcn.demo06; /** * @program: Demo04Random * @description: *
@author: OriginalCoder * @createtime:2020/10/28 22:57 **/ import java.util.
Random; import java.util.Scanner; public class Demo04Random { public static void
main(String[] args) { Random r = new Random(); int randomNum = r.nextInt(100) +
1; //[1,100]; If not +1, That's it 0-99 Scanner sc = new Scanner(System.in); for (int i = 0;
i< 10; i++) { // Limit times System.out.println(" Please enter the number you guessed ："); int guessNum = sc.nextInt
(); if(randomNum < guessNum) { System.out.println(" It's too big ! Please try again "); } else if (
randomNum> guessNum) { System.out.println(" It's too small ! Please try again "); } else { System.out.
println(" Guess right "); break; // If you're right , Don't try again } } System.out.println(" You've tried too many times , game over "); }
}

Technology
Daily Recommendation
views 2