2013-04-17 41 views
0

我在驗證這部分代碼時遇到了問題,錯誤消息沒有正確顯示,如果我只敲了回車鍵,程序將退出,任何幫助表示讚賞。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); 

回答

1

對於多個負表達式中使用的邏輯運算符&&

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

||操作者短路表達式所以while環可以保持活性即使strInput1是空的。在第二個while循環中也不會分配cShipping,這將防止循環退出。

旁白: A do-while loop可以允許兩個循環合併成一個循環。

0

你在你的代碼的單個|這是一個Bitewise Or,而不是邏輯或||

0

所以你的麻煩是驗證你的代碼,而不是代碼本身?我知道我們的第一本能是太急於修正你的代碼,但是我想提供一個我認爲更有利的替代解決方案。

我認爲你的麻煩的解決方案將是重構你的代碼,首先學習良好的編碼習慣和風格。這將有助於您在未來以及任何開發工作。

開始的好地方是here (wikipedia),他們討論了編碼約定和重構。

在粘貼的代碼中,我看到拼寫錯誤,一行說'在此處輸入代碼',並在您的邏輯中存在缺陷。除此之外,還不清楚你的最後一個'if'語句包含第二行:並且雖然縮進顯示它可能,但缺少大括號可以確保其他情況。

應爲以下。(如果這是你確實打算)

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

在一個側面說明,這將是通過使用模塊化,耦合,也許更值得改善您的代碼錯誤檢查/捕獲。