我们经常在日常生活中与朋友玩或者看到过别人玩数字炸弹游戏,非常的有趣。其实这个游戏我们可以通过java把这个数字炸弹游戏编写出来。
这个游戏的功能就是你出个数字、我来猜。
游戏原理如下:
1.后台预先生成一个1-100之间的随机数,用户键盘录入猜数字
2.如果猜对了,打印“恭喜您,答对了”
3.如果猜错了
猜大了:打印“你猜的数字小了!”
猜小了:打印“你猜的数字小了!”
4.直到数字猜到为止,统计猜测次数。
游戏需要使用的知识点:
1.随机数类Random
2.选择结构if
3循环结构while
代码如下:
import java.util.Scanner;
public class guess
{
public static void main(String[] args)
{
// TODO 自动生成的方法存根
int x=(int)(Math.random()*100+1);
Scanner input=new Scanner(System.in);
System.out.println("请输入你猜测的数字:");
int guessint=input.nextInt();
int count=1;
while(guessint!=x)
{
if(guessint<x)
System.out.println("你猜的数字小了!!!!");
else
System.out.println("你猜的数字大了!!!!");
System.out.println("请输入你猜测的数字:");
guessint=input.nextInt();
count++;
}
System.out.println("恭喜你,你猜对了数字"+x+"。一共猜了"+count+"次");
System.out.println("游戏结束!");
一般猜数字使用二分法猜测,约七次可猜到答案。