【问题标题】:Assigning a name to a number为号码分配名称
【发布时间】:2014-11-02 20:59:50
【问题描述】:

我目前正在编写一个涉及随机卡片选择的程序,我想知道是否有办法让程序分别用 jack、queen 和 king 替换数字 11、12 和 13?我可以使用 if 语句来检测大于 10 的值,但这会迫使我编写相同的代码大约 4 次,这似乎适得其反。非常感谢任何和所有回复!

int card0 = (cardGenerator.nextInt(13) + 2);
        int winTest = 4;
        while(winTest > 0)
        {
            Object[] highLowEqual = { "higher", "lower", "equal", "Quit" };
            Object userChoice = JOptionPane.showInputDialog(null,
            "The current card is " + card0 + ". Which do you think the next card will be? Remember: Ace is the highest possible.", "HiLo",
            JOptionPane.INFORMATION_MESSAGE, null,
            highLowEqual, highLowEqual[0]);
            int card1 = (cardGenerator.nextInt(13) + 2);

【问题讨论】:

  • 写一个方法。这就是避免重复编写 4 次相同代码的方法。
  • 使用if 语句,或者switch 语句。

标签: java random naming


【解决方案1】:

有一个知道如何打印自己的Card 类:

public class Card
{
    int rank; 

    // ...

    public String toString()
    {
        switch( rank )
        {
            case 1: return "Ace";
            case 2:
            case 3:
            case 4:
            case 5:
            case 6:
            case 7:
            case 8:
            case 9:
            case 10: return "" + rank;
            case 11: return "Jack";
            case 12: return "Queen";
            case 13: return "King";
            default: return "INVALID CARD RANK";
        }
    }
}

【讨论】:

    【解决方案2】:

    某些代码必须进行替换,并且该代码必须去某个地方。正如 khelwood 评论和 clcto 回答的那样,您可以覆盖 toString() 方法并将替换逻辑放在那里。

    【讨论】:

      猜你喜欢
      • 2018-10-31
      • 2022-10-01
      • 2012-07-31
      • 2020-01-24
      • 2013-05-12
      • 2013-08-02
      • 1970-01-01
      相关资源
      最近更新 更多