Java implementation of guessing the number mini game (limited to the number of times)

This article mainly introduces the implementation of the number guessing game in Java in detail. There is a limit on the number of times. The sample code in the article is very detailed and has a certain reference value. Interested friends can refer to it.

Use code to simulate a mini game of guessing numbers for your reference. The specific content is as follows

Ideas :

1. First, a random number needs to be generated, and once it is generated, it will not change. Use Random's nextInt method

2. Keyboard input is required, so Scanner is used

3. To get the number entered by the keyboard, use the nextInt method in Scanner

4. It is stipulated that only 7 guesses can be made at most, and the number of times is used up and the game is over. Two numbers have been obtained, judge (if):

If it is too big, the prompt is too big, please try again.
If it is too small, the prompt is too small, please try again.
If the guess is correct, the game ends, and the number of guesses is attached.

5. To retry is to do it again, the number of loops is uncertain, use while (true). If the number of cycles is determined, an if statement can be added to control the number of times.

Finally, if you feel unsatisfied, you can add rules and use different codes to achieve better learning effects.

Code:

import java.util.Random;
import java.util.Scanner;

public class Demo01{
 public static void main(String[] args) {
  Random r = new Random();
  int num = r.nextInt(100)+1;
  Scanner sc = new Scanner(System.in);
  for (int i = 0; i < 8; i++) {
   System.out.println("请输入你猜的数字:");
   int gessnum = sc.nextInt();
   if(i==7){
    if(gessnum==num){
     System.out.println("恭喜你,第7次终于猜对啦!");
    }
    else{
     System.out.println("很遗憾!次数用完");
     System.out.println("正确答案是:"+num);
     break;
    }
   }
   if(gessnum>num){
    System.out.println("你猜得太大了!请重试");
   }
   else if(gessnum<num){
    System.out.println("你猜得太小了!请重试");
   }
   else {
    System.out.println("恭喜你,你猜对啦!");
    System.out.println("你一共猜了"+i+"次,继续加油!");
    break;
   }
  }
  System.out.println("游戏结束。");
 }
}

Summary : Although this is a very simple code implementation problem, for beginners, there is still a place to learn more.

The above is the whole content of this article, I hope it will be helpful to everyone's study, thank you all

Guess you like

Origin blog.csdn.net/p1830095583/article/details/114699773