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

如何在简易老虎机Java代码中用单词替换随机数

简易老虎机代码修改方案

以下是修改后的完整代码,实现用水果单词替代随机数,同时修复原代码中的逻辑错误:

import java.util.Scanner;
import java.util.Random;

public class Project1Slot {
    public static void main(String[] args){
        Scanner input = new Scanner(System.in);
        Random random = new Random();
        int amount;
        // 定义水果选项数组
        String[] fruits = {"orange", "apple", "peach", "pineapple"};
        String slot1;
        String slot2;
        String slot3;
        
        System.out.println("Enter the dollar amount here: ");
        amount = input.nextInt();
        
        // 随机获取水果(通过数组索引)
        slot1 = fruits[random.nextInt(fruits.length)];
        slot2 = fruits[random.nextInt(fruits.length)];
        slot3 = fruits[random.nextInt(fruits.length)];
       
        // 输出老虎机结果
        System.out.println(slot1 + "||" + slot2 + "||" + slot3);
        
        // 全匹配判断
        if (slot1.equals(slot2) && slot2.equals(slot3)){
            System.out.println("Congratulations, you won " + "$" + 3 * amount);
        // 两个匹配判断(修复原代码的逻辑错误)
        }else if(slot1.equals(slot2) || slot1.equals(slot3) || slot2.equals(slot3)) {
            System.out.println("Congratulations,you won " + "$" + amount);    
        }else {
            System.out.println("Sorry, you lost");
        }
        
        input.close(); // 关闭Scanner避免资源泄漏
    }
}

修改说明

  • 水果选项管理:用字符串数组fruits统一管理所有水果单词,后续添加或修改水果只需调整数组,无需改动其他逻辑
  • 随机生成水果:通过random.nextInt(fruits.length)生成数组随机索引,再取出对应水果,替代原随机数字逻辑
  • 输出优化:直接输出水果单词,符合需求的显示效果
  • 修复匹配逻辑:原代码中else if里的slot2==3是无效条件(原随机数范围仅0-1),改为slot2.equals(slot3),正确覆盖所有两两匹配场景
  • 规范字符串比较:用equals()方法判断字符串相等,比==更严谨,避免因字符串对象差异导致判断错误
  • 资源回收:添加input.close()关闭输入流,避免资源泄漏

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 08:31:13