如何在JOptionPane.showInputDialog中添加变量

问题描述

我真的是Java和GUI的新手,但是我正在尝试对应用程序实施“猜数字游戏”。 我要在此处更改最大和最小变量 n = Integer.parseInt(JOptionPane.showInputDialog(“选择[%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.@R_650_4045@ION_MESSAGE);
                }
    
                if( n < nRandom )
                {
                    JOptionPane.showMessageDialog(null,"Too Low",JOptionPane.@R_650_4045@ION_MESSAGE);
                }
            }
        } while ( n != nRandom);
        JOptionPane.showMessageDialog(null,"Congrats!! Attempts = "+ nAttempts,"Level finished",JOptionPane.WARNING_MESSAGE);
    }
}

解决方法

根据我的评论,您可能想看看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",JOptionPane.INFORMATION_MESSAGE);
                }
            }
        } while ( n != nRandom);
        JOptionPane.showMessageDialog(null,"Congrats!! Attempts = "+ nAttempts,"Level finished",JOptionPane.WARNING_MESSAGE);
    }
}