【发布时间】:2020-03-08 20:11:24
【问题描述】:
对编码相当陌生,我只想接受整数并显示只允许使用整数的 JOptionPane 警告消息。我曾尝试使用 NumberFormatException 但我不熟悉这种方法。谢谢!
import javax.swing.JOptionPane;
import java.util.Random;
public class GuessingGame
{
public static void main(String[] args)
{
int start = JOptionPane.showConfirmDialog(null, "You must guess a number between 100 and 500 in a set amount of guesses.", "Press 'Yes' to start the guessing game.", JOptionPane.YES_NO_OPTION);
if(start == JOptionPane.YES_OPTION)
{
Random rng = new Random();
int theNumber = rng.nextInt((500-100)+1)+100;
String guess;
int maxAttempt = 1;
int inputNumber;
System.out.println(theNumber);
while(maxAttempt<=4)
{
guess = JOptionPane.showInputDialog(null, "Please input a number between 100-500 you have four chances.");
inputNumber = Integer.parseInt(guess);
try
{
}catch(NumberFormatException e){
JOptionPane.showMessageDialog(null, "You must only enter an integer", "Guessing Game", JOptionPane.WARNING_MESSAGE);
}
if(inputNumber==theNumber)
{
JOptionPane.showMessageDialog(null, "Winner! Guess is correct.", "Guessing Game", JOptionPane.INFORMATION_MESSAGE);
break;
}
else if(inputNumber>theNumber)
JOptionPane.showMessageDialog(null, "Guess was greater than the real number.", "Guessing Game", JOptionPane.WARNING_MESSAGE);
else
JOptionPane.showMessageDialog(null, "Guess was less than the real number.", "Guessing Game", JOptionPane.WARNING_MESSAGE);
maxAttempt++;
}
if(maxAttempt>4)
JOptionPane.showMessageDialog(null, "Game Over. You have exceeded your guessing limit.", "Guessing Game", JOptionPane.ERROR_MESSAGE);
}
else
JOptionPane.showMessageDialog(null, "Quiting Game, press 'Ok' to exit.", "Guessing Game", JOptionPane.INFORMATION_MESSAGE);
}
}
【问题讨论】:
-
您将
try放入while循环中,在您接受第一个int作为输入之前,它应该位于main()方法的开头。 -
这能回答你的问题吗? How to check if a String is numeric in Java