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

Java石头剪刀布游戏代码中stringRounds循环拒收有效值问题求助

问题根因
  • 循环判断条件依赖的int变量rounds仅在循环外赋值一次,循环内部只更新了存储输入的字符串变量stringRounds,未同步将新输入的有效值转为int更新rounds,导致初始输入非法后,循环条件永远为真,进入死循环。
  • 代码缺少java.util.Scanner、java.util.Random的引入声明,直接运行会报类找不到错误。
修复后代码(提示语已翻译为中文)
// 补充缺失的import声明
import java.util.Scanner;
import java.util.Random;

public class RockPaperScissors {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        Random rnd = new Random();
    
        String stringRounds = " ";
    
        System.out.println("欢迎来到石头剪刀布游戏!");
        System.out.println("请输入你想游玩的轮次(1-10范围内):" );
        stringRounds = sc.nextLine();  
        
        int rounds = Integer.parseInt(stringRounds);
        
        while (rounds < 1 || rounds > 10) {
            System.out.println(stringRounds + " 超出范围,请重新输入:");
            stringRounds = sc.nextLine();
            // 同步更新rounds变量值,保证循环判断条件可正常生效
            rounds = Integer.parseInt(stringRounds);
        }
        System.out.println(stringRounds + " 轮没问题,我们开始吧!");
    }
}
优化建议

可新增非数字输入的异常捕获逻辑,避免用户输入字母、符号等非数字内容时,Integer.parseInt方法抛出异常直接终止程序。

内容的提问来源于stack exchange,提问作者Christian F.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 23:45:08