java错误消息未显示

时间:2013-04-17 02:18:25

标签: java

我无法验证我的代码的这一部分,错误信息没有正确延迟,如果我只按了回车键,程序将退出,任何帮助表示赞赏。

    strInput1="";
    strInput1 = JOptionPane.showInputDialog(null,
            "2013 SHIPPING OPTIONS\n\n(O)vernight shipping-$10.00"+
            "\n(T)wo-Day shipping-$7.50\n(P)riority shipping-$5.00"+
            "\n(N)o cost shipping"+
            "\n\nPlease select a shipping option(O,P,T or N) ",
            "Wiliam's Party Store",3);
            if(!strInput1.equals(""))
                JOptionPane.showMessageDialog(null, 
                "You MUST enter O,o,T,t,P,p,N,n",
                "ERROR!!!",0);
            cShipping=(strInput1.toUpperCase().charAt(0));


        while((!strInput1.equals(""))&& !(cShipping=='P')|(cShipping=='T')||(cShipping=='O'))
     {
            JOptionPane.showMessageDialog(null, 
            "You MUST enter O,o,T,t,P,p,N,n",
            "ERROR!!!",0);
            strInput1 = JOptionPane.showInputDialog(null,
            "2013 SHIPPING OPTIONS\n\n(O)vernight shipping-$10.00"+
            "\n(T)wo-Day shipping-$7.50\n(P)riority shipping-$5.00"+
            "\n(N)o cost shipping"+
            "\n\nPlease select a shipping option(O,P,T or N) ",
            "Wiliam's Party Store",3);
            if (!strInput1.equals(""))
            cShipping=(strInput1.toUpperCase().charAt(0));
                    strInput1 = "N";
    }
    PO1.setShipping(cShipping);

3 个答案:

答案 0 :(得分:1)

对于多个否定表达式,请使用逻辑&&运算符:

while (!strInput1.equals("") && cShipping != 'P' && 
                                       cShipping != 'T' && cShipping != 'O')

||运算符会短路表达式,因此while循环即使strInput1为空也可以保持活动状态。此外,cShipping永远不会在第二个while循环中分配{{1}},这将阻止循环退出。

除了: A do-while loop可以允许两个循环合并为一个。

答案 1 :(得分:0)

您的代码中只有|Bitewise Or而不是逻辑或||

答案 2 :(得分:0)

所以你的问题是验证你的代码,而不是代码本身?我知道我们的第一直觉太急于改正你的代码但是我想提供一种替代解决方案我认为更有益。

我认为解决问题的方法是重构代码,首先要学习良好的编码实践和风格。这将有助于您将来以及任何开发工作。

一个好的起点是here (wikipedia) ,他们讨论编码约定和重构。

在您粘贴的代码中,我看到了拼写错误,一行说“在这里输入代码”,以及您逻辑中的缺陷。除此之外,还不清楚你的最后一个'if'语句在哪里包含第二行:虽然缩进表明它可能,但缺少括号可以确保其他方式。

if (!strInput1.equals(""))
        cShipping=(strInput1.toUpperCase().charAt(0));
                strInput1 = "N";

应该是以下......(如果这是你的意图)

if (!strInput1.equals(""))
        cShipping=(strInput1.toUpperCase().charAt(0));
strInput1 = "N";

另一方面,通过使用模块化,耦合以及甚至更多错误检查/捕获来改进代码是值得的。