如何解决如何在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.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);
}
}
解决方法
根据我的评论,您可能想看看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);
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。