使用equalsIgnoreCase在java中显示错误的方法

时间:2013-07-19 00:24:52

标签: java

我是java的新手。我正在搞乱一些代码,以允许它显示错误,而不是整个系统得到一个错误,如果用户输入它不想要的东西,如一堆随机字母。我想使用布尔值,但我不知道从哪里开始。我使用了try和catch一个int,但我不知道如何处理一个布尔值。有人告诉我们一个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);

2 个答案:

答案 0 :(得分:1)

单独使用Boolean#parseBoolean()无法验证字符,因为它会为任何未评估为false的字符串返回true(当然会忽略该情况)。因此,它会返回false垃圾字符,而不是抛出一个解析异常。

因此,您需要使用bdayequalsIgnoreCase()进行测试,以验证用户是否输入了以下两个值中的一个: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!");
}

答案 1 :(得分:0)

我真的不知道JOptionPane,但快速浏览表明您应该使用“ConfirmDialog”而不是“InputDialog”。那应该得到一个int 0,1值而不是你需要解析的String。

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