初学java,猜数字小游戏真不错。
public class 猜数字 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int a,count=0;
int number=(int)(Math.random()*100+1);
do {
a=in.nextInt();
count=count+1;
if(a>number)
System.out.println("偏大");
else if(a<number)
System.out.println("偏小");
}while(a!=number);
System.out.println("恭喜你猜对了,你猜了"+count+"次");
in.close();
}
}
猜数字小游戏的核心 随机数
int number=(int)(Math.random()*100+1);
Math.random() 让计算机随机生成一个[0,1)的实数,乘以100再加一变为随机生成一个[1,101)的实数,(int)强制转换后就成了[1,100]的整数。