gpt4 book ai didi

java - 如何捕获字母并显示错误并且仅显示整数?

转载 作者:行者123 更新时间:2023-12-01 18:03:46 24 4
gpt4 key购买 nike

对编码相当陌生,我只想接受整数并显示仅允许整数的 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-catch 内部调用 Integer#parseInt 。然后,当发生异常时,您需要继续执行 while 循环的下一次迭代。

替换

                inputNumber = Integer.parseInt(guess);
try {
}catch(NumberFormatException e){
JOptionPane.showMessageDialog(null, "You must only enter an integer", "Guessing Game", JOptionPane.WARNING_MESSAGE);
}

                try {
inputNumber = Integer.parseInt(guess);
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null, "You must only enter an integer", "Guessing Game", JOptionPane.WARNING_MESSAGE);
continue;
}

关于java - 如何捕获字母并显示错误并且仅显示整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60591634/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com