用java实现猜数字游戏
/*
如何和用户进行猜数字(10到99的整数)游戏?
思路:
Math类型获得随机数:
Math.random() ---> 可以返回一个double类型的随机数且范围为[0,1.0)
double nember = Math.random() * 90 + 10; --->获得一个[10,100.0)的随机数number
强制类型转换
int number1 = (int)(Math.random() * 90 + 10); --->获得一个[10,99]的随机整数number1
*/
import java.util.Scanner;class GassNumber{public static void main(String[] args){Scanner scan = new Scanner(System.in);System.out.println("请输入你的名字");String name = scan.next();System.out.println(name + "!我可以和你玩猜数字游戏");System.out.println("请输入10到99之间的整数");int x1 = scan.nextInt();int count = 1;//用的是do-while所以第一次猜数也算int num = (int)(Math.random() * 90 + 10);do{if(x1 > num){System.out.println("猜大了");}else if(x1 < num){System.out.println("猜小了");}count ++;x1 = scan.nextInt();}while(num != x1);System.out.println("恭喜你只用了" + count + "次就猜对了!");
}
}
运行结果:

本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
