gpt4 book ai didi

java - "if (int == 1)"不起作用

转载 作者:行者123 更新时间:2023-11-30 02:57:44 25 4
gpt4 key购买 nike

所以我正在尝试学习Java,并且一直在编写一个基于21场比赛游戏的基本程序;每个玩家轮流参加 1、2 或 3 场比赛。最后一场比赛的玩家输了。

本来一切都很顺利,直到我发现当用户即将获胜时,程序却无法进入 final else if陈述;它会跳过它并返回给用户,而计算机不会进行任何匹配。附件是我写的电脑转的方法。

public static int ComputerPlays(int matches){ //Method for the computers turn
int matchesTaken = 0;

if (matches > 7){ matchesTaken = new Random().nextInt(3)+1; }
else if (matches > 4 && matches < 8){ matchesTaken = matches - 4; }
else if (matches < 5){ matchesTaken = matches - 1; }
else if (matches == 1){ matchesTaken = 1; }

System.out.println("Computer takes " + matchesTaken + " matches");
return(matches - matchesTaken);
}

线路else if (matches == 1){ matchesTaken = 1; }这是我遇到问题的地方。任何帮助将不胜感激。

附注我意识到我可以转动 else if进入else声明,但主要是我想了解问题是什么,而不仅仅是解决它。

最佳答案

您应该移动 (matches == 1)之前(matches < 5)健康)状况。在 (matches == 1) 之前无法访问该代码因为 (matches < 5) 满足这个条件还。

更新的代码:

public static int ComputerPlays(int matches){ //Method for the computers turn
int matchesTaken = 0;

if (matches > 7){ matchesTaken = new Random().nextInt(3)+1; }
else if (matches > 4 && matches < 8){ matchesTaken = matches - 4; }
else if (matches == 1){ matchesTaken = 1; }
else if (matches < 5){ matchesTaken = matches - 1; }

System.out.println("Computer takes " + matchesTaken + " matches");
return(matches - matchesTaken);
}

关于java - "if (int == 1)"不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36785720/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com