2013-03-20 94 views
-3

所以我正在編寫一個相當低水平的Java編程的程序。 這是我有什麼用的問題:Java如果-else語句沒有按預期工作

//The String fillText is given a value earlier in the program 
if ("".equals(txa1.getText())) 
{ 
    txa1.setText(fillText); 
    txa1.setVisible(true); 
} 
else if ("".equals(txa2.getText())) 
{ 
    txa2.setText(fillText); 
    txa2.setVisible(true); 
} 
else if ("".equals(txa3.getText())) 
{ 
    txa3.setText(fillText); 
    txa3.setVisible(true); 
} 
else if ("".equals(txa4.getText())) 
{ 
    txa4.setText(fillText); 
    txa4.setVisible(true); 
} 
else if ("".equals(txa5.getText())) 
{ 
    txa5.setText(fillText); 
    txa5.setVisible(true); 
} 
... 

此代碼似乎總是填滿所有的文字區域(txaX)用的fillText方法。 我期待它只執行第一個返回true的語句,然後突破if-else語句。

我試圖用switch-case做,但最終失敗了,因爲在程序運行期間字符串被改變了。

出了什麼問題?

在此先感謝!

+0

它是在這些文本字段的循環或監聽器? – 2013-03-20 16:57:07

+1

看起來問題在於代碼中的其他地方,而不是在這裏。檢查此代碼是否在程序中多次執行(例如在循環中或在某個地方的不同調用中)。 – 2013-03-20 16:57:13

+0

你可以解釋清楚pls ..... – PSR 2013-03-20 16:58:54

回答

0

它是在循環中。定義是導致問題的原因。使用out循環時,它將只轉到一個block。不可能在沒有循環的情況下執行。當我們使用if else時,只有一個block會執行。

0
"".equals(txa1.getText()) 

我覺得上面的條件對每個返回true。

getText()方法總是返回空字符串,即「」;

0

你必須仔細檢查你的條件,如果條件是錯誤的,它將基本上執行前人。 我建議你想想你想要實現什麼的邏輯更多..