java实现猜数游戏
一:java实现随机给出一个1-100的随机数
int num = (int) (Math.random() * 100) + 1;
在java的Math类中有一个方法可以产生0.0—1.0的double类型小数,通过这段代码可以产生一个1-100的随机数
二:java完整代码
import java.util.Scanner;
//Math为基础类不需要导包!
//猜数游戏(1-100)
public class Guess {
public static void main(String[] args) {
@SuppressWarnings("resource")
Scanner scan = new Scanner(System.in);
while (true) {
int num = (int) (Math.random() * 100) + 1;
int count = 0;// 计数器,计算猜的次数
while (true) {
System.out.println("请输入你猜的数(1-100)");
int youGuess = scan.nextInt();
count++;
if (youGuess > num) {
System.out.println("你猜大了");
} else if (youGuess < num) {
System.out.println("你猜小了");
} else {
System.out.println("你猜对了!一共猜了" + count + "次" + "你猜的数为" + youGuess + "随机数为" + num);
System.out.println("GAME OVER!!");
break;
}
}
System.out.println("输入y继续游戏,输入其它退出游戏");
String agin = scan.next();
if (agin.equals("y")) { // 假如输入y,则继续循环,输入其它通过break语句退出循环
} else {
break;
}
}
}
}