Java猜数字游戏,事先随机给出3个100以内的正确答案,然后再输入100以内的数字猜,这个用数组怎么做呢?

2025-04-27 08:55:47
推荐回答(1个)
回答1:

Random r = new Random();
int num[] = new int[3];
for(int i = 0;i<3;i++){
int n = r.nextInt(100);
num[i] = n;
}
System.out.println("请输入数字:");
Scanner s = new Scanner(System.in);
int input = s.nextInt();
boolean res = false;
System.out.println("我猜的数字"+input);
for (int i = 0; i < num.length; i++) {
int j = num[i];
if(j==input)
res = true;
}
if(res)
System.out.println("猜对了");
else
System.out.println("猜错了");
System.out.println("3个正确答案:");
for (int i = 0; i < num.length; i++) {
int j = num[i];
System.out.print(j+" ");
}

运行结果