public class calcButtonHandler3 implements ActionListener
{
public void actionPerformed(ActionEvent a)
{
DecimalFormat num3 = new DecimalFormat(",###.##");
double feet, milli, meters, yards, inches;
String str1 = tFeet.getText();
String str2 = tYards.getText();
String str3 = tInches.getText();
String str4 = tMeters.getText();
String str5 = tMilli.getText();
if (str1 != "")
{
feet = Double.parseDouble(tFeet.getText());
yards = feet / 3;
inches = feet * 12;
milli = feet * 304.8;
meters = feet * 0.3048;
tYards.setText(num3.format(yards));
tInches.setText(num3.format(inches));
tMilli.setText(num3.format(milli));
tMeters.setText(num3.format(meters));
}
else if (str2 != "")
{
yards = Double.parseDouble(tYards.getText());
feet = yards * 3;
inches = yards * 36;
milli = yards * 914.4;
meters = yards * 0.9144;
tFeet.setText(num3.format(feet));
tInches.setText(num3.format(inches));
tMilli.setText(num3.format(milli));
tMeters.setText(num3.format(meters));
}
else if (str3 != "")
{
inches = Double.parseDouble(tInches.getText());
feet = inches * 3;
yards = inches * 36;
milli = inches * 25.4;
meters = inches * 0.0254;
tFeet.setText(num3.format(feet));
tYards.setText(num3.format(yards));
tMilli.setText(num3.format(milli));
tMeters.setText(num3.format(meters));
}
else if (str4 != "")
{
meters = Double.parseDouble(tMeters.getText());
feet = meters * 3.2808399;
inches = meters * 39.37007874;
milli = meters * 1000 ;
yards = meters * 1.0936133;
tFeet.setText(num3.format(feet));
tInches.setText(num3.format(inches));
tMilli.setText(num3.format(milli));
tYards.setText(num3.format(yards));
}
else if (str5 != "")
{
milli = Double.parseDouble(tMilli.getText());
feet = milli * 0.00328084;
inches = milli * 0.03937008;
yards = milli * 0.00109361;
meters = milli / 1000;
tFeet.setText(num3.format(feet));
tInches.setText(num3.format(inches));
tYards.setText(num3.format(yards));
tMeters.setText(num3.format(meters));
}
else
{
JOptionPane.showInputDialog("Please input a number");
}
}
}
如何让按钮切换到其他if语句?当我运行此代码时,如果tFeet字段中没有任何内容,则没有任何反应。
答案 0 :(得分:1)
您的条件并非相互排斥。
if (str1 != "")...
else if (str2 != "")...
else if (str3 != "")...
else if (str4 != "")...
else if (str5 != "")...
如果您需要执行所有语句,那么这些语句应该是五个单独的if
语句而不是一个if...else if
语句。
此外,您应该使用String equals
方法来比较String值。
if (!str1.equals(""))...