【问题标题】:Comparing int's in java比较java中的int
【发布时间】:2017-03-05 16:55:37
【问题描述】:

我有这个脚本可以在 java 中模拟 2 个掷骰子。这会完成两次,一次由用户完成,一次由计算机完成(均自动完成)。程序输出卷并总结它们。但是,我无法使用 if/else 语句来比较掷骰结果并确定获胜者/或平局。到目前为止,我有:

import java.util.Scanner;
import java.util.Random;
import java.text.DecimalFormat;
/*
Program to simulate die roll
*/
public class Dice
{
Scanner scan = new Scanner (System.in);
Random generator= new Random();
int roll1;
int roll2;
int roll3;
int roll4;
int addroll1;
int addroll2;

public void userdieroll() // Simulates users role
{
    roll1 = (generator.nextInt(7) +1); // Generate number from 1-6
    System.out.println("Your first roll is "+roll1+"");// Says users first role
    roll2 = (generator.nextInt(7) +1); // Generate number from 1-6
    System.out.println("Your second roll is "+roll2+"");// Says users second roll
    addroll1=  roll1 +roll2;// Sums users roles
    System.out.println("The sum of your two roles is "+addroll1+" \n");
}
public void compdieroll()// Simulates computers role
{
    roll3 = (generator.nextInt(7) +1); // Generate number from 1-6
    System.out.println("The computers first role is "+roll3+""); // Says computers first role
    roll4 = (generator.nextInt(7) +1); // Generate number from 1-6
    System.out.println("The computers second role is "+roll4+""); // Says computers second role
    addroll2=  roll3 +roll4;// Sums computers roles
    System.out.println("The sum of the computers roles is "+addroll2+""); 
}
public void findwinner()
{
        if (addroll1 == addroll2)
        {
            System.out.println("Its a tie!");
        }
        else
        {   
           if (addroll1 > addroll2)
           {
               System.out.println("You Won!");
           }

           else
           {
               System.out.println("You lost!");
           }

}
}
public static void main(String[] args)
{
    Dice userroll = new Dice();
    userroll.userdieroll();
    Dice comproll = new Dice();
    comproll.compdieroll();
    Dice looper = new Dice();
    looper.findwinner();

}

}

【问题讨论】:

  • roll1 = (generator.nextInt(7) +1); // Generate number from 1-6,嗯,没有。生成一个从 0 到 6 的数字,然后加一个,将得到数字 1 到 7(含)。
  • 是啊哎呀我的不好的好收获

标签: java if-statement int


【解决方案1】:

每次调用方法时,您都会创建一个新的Dice 对象。当您这样做时,您不会将addroll1addroll2 存储在同一个对象中,因此.findwinner() 在您没有在@ 中存储任何值的第三个对象中无法按预期工作是很自然的987654325@ 和addroll2。要解决此问题,请对所有三种方法使用相同的 Dice 对象,如下所示:

Dice tester = new Dice();
tester.userdieroll();
tester.compdieroll();
tester.findwinner();

【讨论】:

  • 谢谢!我没有意识到这一点!仔细想想就明白了!
【解决方案2】:

嗯,乍一看,您正在实例化三个不同的对象。 findwinner() 正在处理 addroll1 = 0addroll2 = 0,因为 0 是此类属性的默认值。

如果你想处理来自不同对象的相同数据,你需要创建属性static。 无论如何,正如其他人建议的那样,在单个实例上完成这项工作。

【讨论】:

  • 创建属性static 是一种糟糕的方法。一个不应该保持可变的静态状态;这给您带来了全局变量的所有痛苦,例如缺乏可测试性或可伸缩性,以及失去对对象生命周期的控制。 @UnknowableIneffible [原文如此] 有更好的解决方案。
  • 我知道。正如我所说,最好的方法是使用单个实例及其属性。但是 OP 使用了三个不同的对象,所以静态是完全可以接受的。
  • 我建议没有建议“静态可变状态”反模式的答案是可以接受的,而不是建议该反模式的答案。
  • 您可以考虑可接受的 UnknowableIneffible 答案,这很好。我再说一遍,我只是告诉 OP Java 是如何工作的。
【解决方案3】:

只是为了让您了解我将如何实现它(拥有大约 20 年的 Java 编程经验):

package nl.owlstead.stackoverflow;

import java.util.Random;

/*
 * Program to simulate a double die roll.
 */
public class DiceGame {
    private Random generator = new Random();

    enum Result {
        LOSER,
        TIE,
        WINNER;
    }

    public DiceGame() {
        // nothing to do in constructor
    }

    public int rollDice() {
        int zeroToFive = generator.nextInt(6);
        int oneToSix = zeroToFive + 1;
        return oneToSix;
    }

    public Result findWinner(int totalRollComp, int totalRollUser) {
        if (totalRollComp > totalRollUser) {
            return Result.LOSER;
        }

        if (totalRollComp < totalRollUser) {
            return Result.WINNER;
        }

        return Result.TIE;
    }

    public static void main(String[] args) {
        DiceGame game = new DiceGame();
        int firstRollComp = game.rollDice();
        int secondRollComp = game.rollDice();
        int totalRollComp = firstRollComp + secondRollComp;
        System.out.printf("Comp rolled: %d and %d, totalling %d%n", firstRollComp, secondRollComp,
                totalRollComp);

        int firstRollUser = game.rollDice();
        int secondRollUser = game.rollDice();
        int totalRollUser = firstRollUser + secondRollUser;
        System.out.printf("User rolled: %d and %d, totalling %d%n", firstRollUser, secondRollUser,
                totalRollUser);

        Result userResult = game.findWinner(totalRollComp, totalRollUser);
        switch (userResult) {
        case LOSER:
            System.out.println("You lost!");
            break;
        case TIE:
            System.out.println("Its a tie!");
            break;
        case WINNER:
            System.out.println("You Won!");
            break;
        }
    }
}

特别有用的是使用尽可能少的字段。正如您已经发现的那样,使用字段(在程序中代表 state)是非常危险的。如果你可以避免状态,你应该这样做。所以在这个程序中只有一个字段:随机数生成器(当然我会改用new SecureRandom())。

此外,它还显示了为变量选择好名称和拆分输出 (System.out) 和游戏本身的力量。除此之外,我尝试不介绍太多技术,但我无法抗拒使用枚举作为结果并使用printf 来简化各种println 语句。

【讨论】:

  • 很好的答案,说明了几个最佳实践。除了初始化之外,在构造函数中什么都不做是很常见的违规行为。
【解决方案4】:

仅使用一个对象,您正在创建 3 个骰子,并且这些值不会在实例之间静态共享...

这将起作用:

Dice userroll = new Dice();
userroll.userdieroll();
userroll.compdieroll();
userroll.findwinner();

【讨论】:

    【解决方案5】:

    在您的班级中,既有用户骰子变量,也有计算机骰子变量。 在您的主目录中,您应该只创建一个类:

    Dice d = new Dice();
    d.userdieroll();
    d.compdieroll();
    d.findwinner();
    

    当您编写代码时,您的代码会使用三个不同的roll1roll2... 创建三个不同的 Dice 实例

    ...
    Dice looper = new Dice();
    looper.findwinner();
    

    它将变量looper.addroll1looper.addroll2(即looper 类中的变量)进行比较,但在填充userroll.addroll1comproll.addroll2 之前的行中,这些变量仍然为0(默认值)。

    Vjncenzo

    【讨论】:

    • OP 的代码“创建三个不同的类”是错误的,addroll1“变量未初始化”也是错误的。
    猜你喜欢
    • 2014-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多