所以我是java新手,我正在尝试使用try and 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");
}
}