所以我是java新手,我正在尝试使用try和catch。例如,如果我询问用户有多少葡萄,并且他们输入了一堆字母,它将显示一个错误对话框,而不仅仅是出现系统错误。我可以使用扫描仪来完成此操作,但不能使用 JOptionPane。我真的希望出现一个对话框,这就是我尝试使用 JOptionPane.showInputDialog 的原因。
扫描仪可以工作...=
import java.util.Scanner;
class test {
public static void main (String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("How many grapes do u have?");
int grapes = 1;
try
{
grapes = input.nextInt();
}
catch (Exception e)
{
System.out.println("Good job Sherlock you broke the program");
return;
}
int mg;
if (grapes >= 100)
mg = 1;
else
mg = 2;
switch (mg){
case 1: System.out.println("You got a lot of grapes");
break;
case 2: System.out.println("You brarely got any grapes");
break;
}
}
}
JOptionPane 不起作用...
import javax.swing.JOptionPane;
public class bday
{
public static void main(String[] args)
{
String age = "0";
try
{
age = JOptionPane.showInputDialog("What was your age yesterday?");
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null, "Thanks a lot, you broke it. CYA later.");
return;
}
int iage = Integer.parseInt(age);
String bday = "0";
try
{
bday = JOptionPane.showInputDialog("Was yesterday your B-Day? (True or False)");
}
catch (Exception e)
{
JOptionPane.showMessageDialog(null, "WHY U MESS UP PROGRAM???.... BYE BYE!!");
return;
}
boolean bage = Boolean.parseBoolean(bday);
if (bage == true){
iage += 1;
JOptionPane.showMessageDialog(null, "You are now " + iage);
}
else if (bage == false){
JOptionPane.showMessageDialog(null, "Happy unbirthday!");
}
if (iage ==10){
JOptionPane.showMessageDialog(null, "Congrats, double digits!");
}
if (iage >19){
JOptionPane.showMessageDialog(null, "U aint a Teenager");
}
else if (iage < 13)
JOptionPane.showMessageDialog(null, "U aint a Teenager");
}
}
最佳答案
你正在尝试/捕获错误的东西。您应该将解析语句放在 try block 中,因为这会引发异常。
例如,不是
String age = "0";
try
{
age = JOptionPane.showInputDialog("What was your age yesterday?");
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null, "Thanks a lot, you broke it. CYA later.");
return;
}
int iage = Integer.parseInt(age);
而是:
String age = JOptionPane.showInputDialog("What was your age yesterday?");
try {
iage = Integer.parseInt(age);
} catch (NumberFormatException nfe) {
// show error
}
此外,您应该避免捕获Exception
,而应该只捕获特定的异常,此处为NumberFormatException
。
编辑
在评论中你问:
One more question, should i do the same with the boolean?
在解析时, boolean 类型有点棘手(在我看来)。要了解 Boolean.parseBoolean(...)
的工作原理,请查看 Boolean API ,特别是 parseBoolean 方法。您将看到,如果输入的文本没有意义,它不会抛出 NumberFormatException。 API 会告诉您实际上返回了什么。 try/catch block 在这里不起作用。如果您需要捕获错误,请考虑使用 String 的 equalsIgnoreCase(...)
。
关于java - 如果用户输入随机字母,如何给出对话框错误 JOptionPane,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17735895/