Common Java API's Ramdom
Ramdom class used to generate random numbers . Step three is to use;
1. Package guide
import java.util.Random;
2. Create
R & lt = the Random new new the Random (); // small empty can which comprises
3. Use
Obtaining a random array int (int all ranges are ranges plus or minus two); int NUM = r.nextInt (); obtaining a random number int (parameter represents the range, closing the left and right open interval); int NUM = r.nextInt (3 ); in fact, the meaning is represented by: [ 0,3), which is 0-2
Guessing game with simulation codes
Ideas:
1. First need to generate a random number, and does not change once produced. Random and nextInt with methods (for generating a random number)
2. require keyboard input, it uses Scanner
3. acquired numeric keyboard input, among nextInt method using Scanner (input)
4. The two numbers have been, decision making (if )a bit:
- If too small, too large tips, and the retry
- If too small, suggesting that small, and the retry
- If you guessed, the game is over
The retry is again, uncertain cycles, with while (true).
Import java.util.Random Import java.util.Scanner public class CaiNiao { public static void main {(String [] args) the Random R & lt = new new the Random (); int randomNum r.nextInt = (100) + 1'd; // [ 1,100] Scanner sc = new new Scanner (System.in); the while ( to true ) { System.out.println ( "Please enter your guess numbers:" ); int gussNum = sc.nextInt (); // keyboard guess digital IF (guessNum> randomNum) { System.out.println ( "too much, please try again." ); } The else IF (gussNum < randomNum) { System.out.println ( "too small, please try again." ); } The else { the System. out.println ( "Congratulations, you guessed it" ); BREAK ; // If you guessed, not retry } } System.out.println ( "game over!" ); } }
Reproduced in: https: //www.cnblogs.com/cainiao-chuanqi/p/11097354.html