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

Java代码问题:输出数组随机字符串后if与else if分支未执行

问题分析与修复:石头剪刀布代码分支不执行问题

你的Java石头剪刀布代码在输出电脑随机选择的选项后,所有if/else if分支都无法触发执行,核心原因是错误地将随机索引值转成字符串和数组元素比较,而不是直接使用数组中对应的选项字符串。

关键错误点

  • 所有判断逻辑中,你把随机生成的索引zufall(值为0/1/2)转成字符串"0"/"1"/"2",然后去和Pos[1]("Stein")这类实际选项字符串比较,两者永远不可能相等,导致所有分支都无法命中。
  • 存在重复的else if分支:输入Pos[1]且电脑选Pos[0]的情况被写了两次,一次输出"Gewonnen"一次输出"Verloren",逻辑矛盾。

修复后的完整代码

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

public class ScherreSteinPapier {
    public static void main(String[] args) {
        String[] pos = {"Schere", "Stein", "Papier"};
        Scanner scanner = new Scanner(System.in);
        
        // 获取用户输入并去除首尾空格
        String eingabe = scanner.nextLine().trim();
        Random random = new Random();
        
        // 生成电脑选择的索引并获取对应字符串
        int zufall = random.nextInt(pos.length);
        String computerChoice = pos[zufall];
        System.out.println(computerChoice);
    
        // 判断胜负逻辑
        if (eingabe.equals(computerChoice)) {
            System.out.println("Gleichstand");
        } 
        else if (eingabe.equals(pos[0]) && computerChoice.equals(pos[1])) {
            System.out.println("Verloren");
        } 
        else if (eingabe.equals(pos[0]) && computerChoice.equals(pos[2])) {
            System.out.println("Gewonnen");
        } 
        else if (eingabe.equals(pos[1]) && computerChoice.equals(pos[0])) {
            System.out.println("Gewonnen");
        } 
        else if (eingabe.equals(pos[1]) && computerChoice.equals(pos[2])) {
            System.out.println("Verloren");
        } 
        else if (eingabe.equals(pos[2]) && computerChoice.equals(pos[1])) {
            System.out.println("Gewonnen");
        } 
        else if (eingabe.equals(pos[2]) && computerChoice.equals(pos[0])) {
            System.out.println("Verloren");
        } 
        else {
            System.out.println("Fehler");
        }
        
        scanner.close();
    }
}

修复说明

  1. 新增computerChoice变量:直接存储电脑选择的字符串(pos[zufall]),后续判断全部基于该字符串比较,避免索引和字符串的错误对比。
  2. 修正所有判断条件:将String.valueOf(zufall)替换为computerChoice,直接比较用户输入和电脑选择的字符串。
  3. 修复重复分支:删除了重复的eingabe.equals(pos[1]) && ...分支,补充了正确的电脑选pos[2]的判断逻辑。
  4. 优化输入判断:将最后嵌套的多条件判断简化为else,更简洁清晰。
  5. 添加scanner.close():释放资源,符合代码规范。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 06:05:21