gpt4 book ai didi

java - 为什么我的 if else 语句不执行?

转载 作者:行者123 更新时间:2023-12-02 03:13:58 25 4
gpt4 key购买 nike

首先,我发现另外两个线程也有类似的问题。问题是他们没有使用 right equal sign for string而不是formatting the if statements correctly针对他们的特殊问题。

对于我的作业,我需要创建一个名为 Pig 的游戏,其中玩家与计算机在掷骰子对中首先获得 100 分。如果玩家一回合掷出 1 分,则他们不会获得额外分数。如果玩家掷出两个 1,则他们将失去所有分数。我还没有对计算机的回合进行编码,只是关注玩家。请告诉我我做错了什么。预先非常感谢您。

import java.util.Scanner;
public class FourFive
{
public static void main (String[] args)
{
Pigs myopp = new Pigs();
Scanner scan = new Scanner (System.in);
final int Round = 20;
int num1, num2;

int roundTotal = 0;
int playerTotal = 0;
int compTotal = 0;
int win = 100;
int turnOver = 1;
Pigs die1 = new Pigs();
Pigs die2 = new Pigs();
String play = "y";
System.out.println("Type y to play");
play = scan.nextLine();
<小时/>
    while (play.equalsIgnoreCase("y"))
{
for (int roll = 1; roll <= 6; roll++)//Each die has 6 sides
{
num1 = die1.roll();//rolls first die
num2 = die2.roll();//rolls second die
int points = num1 + num2;// adds dies up to get total for this turn
System.out.println("You roll " + num1 + " and " + num2);

if (num1 == 1 || num2 == 1)//If either of the dies roll 1, no points
points += 0;
else if (num1 == 1 && num2 == 1)//if both are 1, lose ALL points
playerTotal = 0;
else
System.out.println("you earned " + points + " this round");

playerTotal += points; total number of points per round added
System.out.println("You have a total of " + playerTotal);


System.out.println("Type y to play");
play = scan.nextLine();
}
}
}
}

我的输出:

Type y to play
y
You roll 4 and 2
you earned 6 this round
You have a total of 6
Type y to play
y
You roll 6 and 5
you earned 11 this round
You have a total of 17
Type y to play
y
You roll 1 and 1
You have a total of 19 //total should be 0 because of the two 1's
Type y to play
y
You roll 6 and 3
you earned 9 this round
You have a total of 28
Type y to play
y
You roll 1 and 1
You have a total of 30 //total should be 0 because of the two 1's
Type y to play
y
You roll 6 and 4
you earned 10 this round
You have a total of 40
Type y to play
y
You roll 5 and 2
you earned 7 this round
You have a total of 47
Type y to play
y
You roll 5 and 1
You have a total of 53 //shouldn't add any additional points because of the "1"
Type y to play

最佳答案

如果 num1 为 1,则第一个 if 条件采用该值。它不会检查“else if”条件。类似地,如果 num2 为 1,则 if 条件采用该值。所以把你的 && 条件放在第一位。

        if (num1 == 1 && num2 == 1)//if both are 1, lose ALL points
playerTotal = 0;
else if (num1 == 1 || num2 == 1)//If either of the dies roll 1, no points
points += 0;
else
System.out.println("you earned " + points + " this round");

关于java - 为什么我的 if else 语句不执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40602232/

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