使用Java的循环和分支结构来创作一个猜数字的小游戏
需求
程序自动生成一个1-100之间的数字,使用程序实现猜出这个数字是多少?
当猜错的时候根据不同情况给出相应的提示
如果猜的数字比真实数字大,提示你猜的数据大了
如果猜的数字比真实数字小,提示你猜的数据小了
如果猜的数字与真实数字相等,提示恭喜你猜中了
代码示例 :
import java.util.Scanner;
public class CaiShuZi {
public static void main(String[] args) {
int result = (int) (Math.random() * 100);
System.out.println("*************猜数字小游戏*************");
int contral = 0;
int totle = 0;
int ci = 0;
while (contral == 0) {
System.out.println("请输入一个1-100之中的数字");
ci++;
Scanner sc = new Scanner(System.in);
int cai = sc.nextInt();
if (cai > result) {
System.out.println(" 不好意思,猜大了");
} else if (cai < result) {
System.out.println("不好意思,猜小了");
} else {
System.out.println("恭喜你!猜对了");
System.out.println("一共猜了" + ci + "次");
System.out.println("是否继续,继续请输入0,退出请输入1");
totle++;
Scanner cc = new Scanner(System.in);
contral = cc.nextInt();
}
}
System.out.println("一共玩了" + totle + "局猜数字小游戏");
}
}