In order to add some fun to the process of learning Java! I will occasionally write some interesting programs and share them with you. If there are any errors or improvements in the code, please correct me.
Meet is [Apefen] If you have a more interesting program, please share it in the comment area, thank you very much!
Don't talk nonsense about GO! GO! GO!
- Formula to generate random integer
(int)(Math.random()*(b-a+1) + a);
- Generate random number: [1,100]
int random = (int)(Math.random()*100 + 1);
After knowing how to generate random integers, then we can add some judgments and loop statements to solve the Java number guessing game:
Guess the number mini game complete code
import java.util.Scanner;
/**
* @Title GuessGame:猜数字小游戏
* @Description
* @Author 星空之路Star
* @Date 2021/3/20 14:07
* @Version V1.0
*/
public class GuessGame {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int random = (int)(Math.random()*100 + 1); //产生一个随机数 [1,100]
System.out.println("-------------------------------------------------------------");
System.out.println("\t\t\t\t\t【 欢迎来到猜字游戏 】");
System.out.print("\t\t\t\t请选择你的幸运次数(推荐6次):");
int maxCount = scan.nextInt(); //输入幸运次数
System.out.println("\t本次猜字游戏您一共有 " + maxCount + " 次机会,所猜数字的范围是:[1,100]");
System.out.println("-------------------------------------------------------------");
System.out.print("请输入所猜数字:");
int num = scan.nextInt(); //第一次输入
for (int i = 2; i <= maxCount; i++) {
if (num < random) {
System.out.println("对不起!输入数字过小,你还剩 " + (maxCount - i + 1)+ " 次机会!");
} else if (num > random) {
System.out.println("对不起!输入数字过大,你还剩 " + (maxCount - i + 1)+ " 次机会!");
} else {
System.out.println("\n恭喜您,您仅用了 " + (i - 1) + " 次机会就猜对了!!!");
break;
}
System.out.print("请输入所猜数字:");
num = scan.nextInt(); //重新输入
if (i == maxCount) {
System.out.println("\nsorry!您的幸运次数不太给力!本次游戏结束!");
}
}
}
}