【问题标题】:How do I add variables in JOptionPane.showInputDialog如何在 JOptionPane.showInputDialog 中添加变量
【发布时间】:2020-12-03 06:07:49
【问题描述】:

我对 Java 和 GUI 很陌生,但我正在尝试将“猜数字游戏”应用到应用程序中。 我想在这里更改 max 和 min 变量 n = Integer.parseInt(JOptionPane.showInputDialog ("Choose a number between [%d,%d]:"), min, max); 使游戏更轻松。 显然这是行不通的,但这是最终目标。有什么建议吗?谢谢

import javax.swing.JOptionPane;
import javax.swing.JTextField;

public class guessTheNumber {
    public static void main(String[] args) {
        int nAttempts= 0, min = 0, max = 100;
        int n = 0, nRandom = (int)( Math.random() * (( max - min ) + 1 )) + min;
        do
        {
            nAttempts++;
            n = Integer.parseInt(JOptionPane.showInputDialog ("Choose a number between [%d,%d]:"), min, max);
            
            if ( n != nRandom)
            {
                if( n > nRandom )
                {
                    JTextField.
                    JOptionPane.showMessageDialog(null, "Too High","Wrong Number", JOptionPane.INFORMATION_MESSAGE);
                }
    
                if( n < nRandom )
                {
                    JOptionPane.showMessageDialog(null, "Too Low","Wrong Number", JOptionPane.INFORMATION_MESSAGE);
                }
            }
        } while ( n != nRandom);
        JOptionPane.showMessageDialog(null, "Congrats!! Attempts = "+ nAttempts,"Level finished", JOptionPane.WARNING_MESSAGE);
    }
}

【问题讨论】:

标签: java swing jtextfield joptionpane


【解决方案1】:

根据我的评论,您可能想看看 String.format

免责声明:我尚未测试代码,但它应该可以正常工作。

import javax.swing.JOptionPane;
import javax.swing.JTextField;

public class guessTheNumber {
    public static void main(String[] args) {
        int nAttempts= 0, min = 0, max = 100;
        int n = 0, nRandom = (int)( Math.random() * (( max - min ) + 1 )) + min;
        do
        {
            nAttempts++;

//change is on the following line

            n = Integer.parseInt(JOptionPane.showInputDialog (String.format("Choose a number between [%d,%d]:", min, max)));
            
            if ( n != nRandom)
            {
                if( n > nRandom )
                {
                    JTextField.
                    JOptionPane.showMessageDialog(null, "Too High","Wrong Number", JOptionPane.INFORMATION_MESSAGE);
                }
    
                if( n < nRandom )
                {
                    JOptionPane.showMessageDialog(null, "Too Low","Wrong Number", JOptionPane.INFORMATION_MESSAGE);
                }
            }
        } while ( n != nRandom);
        JOptionPane.showMessageDialog(null, "Congrats!! Attempts = "+ nAttempts,"Level finished", JOptionPane.WARNING_MESSAGE);
    }
}

【讨论】:

  • 你有什么改变吗?
  • 是的,再次检查代码,我添加了一个注释行,说明它在哪里发生了变化
猜你喜欢
  • 2020-02-05
  • 2017-09-11
  • 2018-10-05
  • 2022-10-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多