2013-03-20 89 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

你必须仔细检查你的条件,如果条件是错误的,它将基本上执行前人。 我建议你想想你想要实现什么的逻辑更多..