0

我是java新手。如果用户输入了它不想要的东西,比如一堆随机字母,我正在弄乱一些代码以允许它显示错误而不是整个系统出现错误。我想使用布尔值,但我不知道从哪里开始。我使用了整数的尝试和捕获,但我不确定如何处理布尔值。有人告诉我们一个 equalsIgnoreCase,但我不知道在哪里添加它。非常感谢您的帮助。

import javax.swing.JOptionPane;

public class bday
{
    public static void main(String[] args)
    {
        String age = "0";

        age = JOptionPane.showInputDialog("What was your age yesterday?");

        int iage = 1;

        try
        {
            iage = Integer.parseInt(age);
        }
        catch(Exception e)
        {
            JOptionPane.showMessageDialog(null, "Thanks a lot, you broke it. CYA later.");
            return;
        }   

        String bday = "0";

         bday = JOptionPane.showInputDialog("Was yesterday your B-Day? (True or False)");


         try
         {
             bage = Boolean.parseBoolean(bday);
         }
         catch (Exception e)
         {
            JOptionPane.showMessageDialog(null, "WHY U MESS UP PROGRAM???.... BYE BYE!!");
            return;
         }

        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");          

    }
}

我在搞什么...

String bday = "0";
String str1 = "true";
String str2 = "false";

 bday = JOptionPane.showInputDialog("Was yesterday your B-Day? (True or False)");


  boolean bage = bday.equalsIgnoreCase(str1);
  boolean bage2 = bday.equalsIgnoreCase(str2);

if (bage == true){
    iage += 1;
    JOptionPane.showMessageDialog(null, "You are now " + iage);
4

2 回答 2

1

单独使用Boolean#parseBoolean()无法验证字符,因为它返回false任何不计算结果的字符串true(当然忽略大小写)。因此,它也会返回false垃圾字符,而不是抛出解析异常。

因此,您需要测试bdayusingequalsIgnoreCase()以验证用户是否输入了以下两个值之一:truefalse. 这不再需要您处理异常,因此try-catch现在不需要。

if (bday.equalsIgnoreCase("true") || bday.equalsIgnoreCase("false")) {
    bage = Boolean.parseBoolean(bday);
} else {
    JOptionPane.showMessageDialog(null, "Invalid choice: Enter true or false.");
    return;
}

if (bage){ // bage == true is unnecessary
    iage += 1;
    JOptionPane.showMessageDialog(null, "You are now " + iage);
} else { // no need to check the condition again
    JOptionPane.showMessageDialog(null, "Happy unbirthday!");
}
于 2013-07-19T00:41:40.983 回答
0

我不太了解 JOptionPane,但快速浏览一下,您可能应该使用“ConfirmDialog”而不是“InputDialog”。这应该为您提供一个 int 0,1 值,而不是您需要解析的字符串。

http://docs.oracle.com/javase/7/docs/api/javax/swing/JOptionPane.html#showConfirmDialog(java.awt.Component, java.lang.Object)

于 2013-07-19T00:37:11.743 回答