You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java如何实现循环直到用户输入值匹配randomNumber?

问题解答

实现方案

你可以通过循环包裹用户输入与判断逻辑,实现输入不匹配就反复重试的需求。另外原代码存在随机数范围与提示输入范围不匹配的问题:Math.floor(Math.random() * 6)生成的是05的整数,和提示的「输入15的数字」不一致,以下代码会同步修正该问题:

package com.arwa.basicExcercisePart1;

import java.util.Scanner;

public class RandomCheck {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        // 调整随机数范围为1-5,和提示的输入范围匹配
        Integer randomNumber = (int) Math.floor(Math.random() * 5) + 1;
        int number;
        
        while (true) {
            System.out.println("Enter a number from 1 to 5: ");
            number = scan.nextInt();
            if (number == randomNumber) {
                System.out.println("Wow, The entered number matched with the Random Number.");
                // 匹配成功,跳出循环
                break;
            } else {
                System.out.println("Sorry, The number you entered did not match with the Random Number, Try Again.");
            }
        }
        // 释放Scanner占用的资源
        scan.close();
    }
}

修改点说明

  • 用while(true)构建死循环包裹用户输入、结果判断逻辑,保证用户猜错时会自动触发重试
  • 当用户输入和随机数匹配时,调用break关键字跳出循环,结束程序
  • 随机数生成逻辑调整为(int) Math.floor(Math.random() * 5) + 1,确保生成的随机数范围为1~5,和提示的输入范围匹配
  • 最后添加scan.close()语句,释放Scanner占用的系统资源

如果你不想使用死循环+break的写法,也可以用以下方式实现:

package com.arwa.basicExcercisePart1;

import java.util.Scanner;

public class RandomCheck {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        Integer randomNumber = (int) Math.floor(Math.random() * 5) + 1;
        // 初始值设置为不在1~5范围内的数即可
        int number = 0;
        
        while (number != randomNumber) {
            System.out.println("Enter a number from 1 to 5: ");
            number = scan.nextInt();
            if (number == randomNumber) {
                System.out.println("Wow, The entered number matched with the Random Number.");
            } else {
                System.out.println("Sorry, The number you entered did not match with the Random Number, Try Again.");
            }
        }
        scan.close();
    }
}

如果需要中文交互提示,直接替换对应位置的英文字符串即可。

内容的提问来源于stack exchange,提问作者Aravind Viswanathan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.14 22:24:09