【问题标题】:How do I get my programme to display integers as strings?如何让我的程序将整数显示为字符串?
【发布时间】:2014-11-11 22:31:35
【问题描述】:

` 程序会随机生成一张卡片,你必须猜测下一张生成的卡片是高于还是低于或等于 目前它只输出数字而不是卡片的名称 当整数“currentCard”和“nextCard”对应于 1(ace)、11(jack)、12(queen) 和 13(king) 的值时,我希望它显示卡片的名称

    Random  generator = new Random();
    int currentCard = generator.nextInt((KING-ACE)+1)+ACE;
    generator = new Random();
//ace = 1, king = 13, queen = 12, jack = 11
    while(count<GUESSES_TO_WIN)

    {

        int nextCard = generator.nextInt((KING-ACE)+1)+ACE;
        //here i want it to display "king" if the number generated is 13, "ace" if its 1,etc
                 String inputGuess = JOptionPane.showInputDialog(null,               
                "Your current card is " +currentCard + ". " +
                "Guess if the next card is higher, lower or equal to your current card."
                +"\n" + (4-count) + " more guesses until you win!");
        Scanner inputScanner = new Scanner (inputGuess);
        guess = inputScanner.nextLine();
        if(guess.equalsIgnoreCase("higher")&&
                (currentCard<nextCard))

        {
            JOptionPane.showMessageDialog(null,
                    guess +" is correct. The next card was " + nextCard);
            inputScanner.close();
            currentCard = nextCard;
            count++;
        }
        else if (guess.equalsIgnoreCase("lower") &&
                (currentCard>nextCard))
        {
            JOptionPane.showMessageDialog(null,
                    guess +" is correct. The next card was " + nextCard);
            inputScanner.close();
            currentCard = nextCard;
            count++;
        }
        else  if (guess.equalsIgnoreCase("equal to") &&
        (currentCard == nextCard))
        {
            JOptionPane.showMessageDialog(null,
                    guess +" is correct. The next card was " + nextCard);
            inputScanner.close();
            currentCard = nextCard;
            count++;`

目前它只输出数字而不是卡片的名称

【问题讨论】:

  • 考虑花时间正确格式化您的代码,以便我们可以看到您要执行的操作。
  • 是的,对不起,我目前正在尝试这样做
  • 即使代码格式正确,也缺少实际问题。你应该用正确的语言标记问题。
  • 我想我修好了。抱歉,我是新手。

标签: java string integer


【解决方案1】:

使用枚举来表示扑克牌的集合和数字到名称的映射。请参阅 Enum 上的 Javadocs:https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html

【讨论】:

  • 除了使用枚举之外还有其他方法吗?这是一个任务,我不认为它应该知道 Enums
  • 你可以创建一个方法,使用 switch 语句检查它是哪个整数并返回适当的字符串。请参阅:docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html
  • 正如我的 comp101 教授所说:试试看!最好的学习方法是试用代码。
猜你喜欢
  • 2018-01-26
  • 2020-03-17
  • 1970-01-01
  • 1970-01-01
  • 2012-03-02
  • 2022-08-18
  • 2020-01-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多