编写一个猜数字游戏程序:

  • 程序随机生成1~100之间的整数;
  • 用户在命令行中输入猜测整数;
  • 根据用户输入给出相应提示:“猜打了”、“猜小了”、“猜对了”;
  • 可让用户再次输入整数游戏,直到提示“猜对了”
  • 统计用户猜测的次数,在猜对时,输出次数统计:“共次了:x次”。
package test;
import java.util.*;
public class test_2 {

	public static void main(String[] args) {
		int a;
		a=(int)(1+Math.random()*100);//1-99,加一是因为要从1开始,不然从0开始;
		Scanner input=new Scanner(System.in);
		int d=0;
		while(true)//如果不弹出就无限循环;
		{
		int b=input.nextInt();
		if(a>b)
		{
			System.out.println("猜小了");
			d++;
		}
		if(a<b)
		{
			System.out.println("猜大了");
			d++;
		}
		if(a==b)
		{
			System.out.println("猜对了");
			break;//跳出循环;
		}}
		System.out.println("猜的次数为: " + d);
	}

}

编写一个猜数字游戏程序: