import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JLabel;
import javax.swing.JButton;
import javax.swing.JPanel;public class convert {
JLabel label1;
JTextField text;
public static void main(String[] args) {
convert con = new convert();
con.go();
}
public void go() {
JFrame frame = new JFrame("convert Celsius");
JButton button = new JButton("Convert");
JLabel label = new JLabel("Celsius");
label1 = new JLabel("Fahrenheit");
text = new JTextField(10);
JPanel panel = new JPanel();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(panel);
panel.add(text);
panel.add(label);
panel.add(button);
panel.add(label1);
button.addActionListener(new buttonAction());
frame.setSize(500,500);
frame.setVisible(true);
} class buttonAction implements ActionListener {
public void actionPerformed (ActionEvent e) {
String x = text.getText();
if (x.length() != 0) {// if (x != null || x != "") is incorrect!
int fahrenheit = (int) (Double.parseDouble(text.getText()) * 1.8 + 32);
label1.setText(fahrenheit + " Fahrenheit");
text.setText("");
text.requestFocus();
}
else {
label1.setText("No Celsius input");
text.requestFocus();
}
}
}
}
如果把if的条件判断改为 x != null 或者 x != "",都是错误的,但是用x.length()可以判断,那么为空时读取的值到底是多少呢?
import java.awt.event.ActionEvent;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JLabel;
import javax.swing.JButton;
import javax.swing.JPanel;public class convert {
JLabel label1;
JTextField text;
public static void main(String[] args) {
convert con = new convert();
con.go();
}
public void go() {
JFrame frame = new JFrame("convert Celsius");
JButton button = new JButton("Convert");
JLabel label = new JLabel("Celsius");
label1 = new JLabel("Fahrenheit");
text = new JTextField(10);
JPanel panel = new JPanel();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(panel);
panel.add(text);
panel.add(label);
panel.add(button);
panel.add(label1);
button.addActionListener(new buttonAction());
frame.setSize(500,500);
frame.setVisible(true);
} class buttonAction implements ActionListener {
public void actionPerformed (ActionEvent e) {
String x = text.getText();
if (x.length() != 0) {// if (x != null || x != "") is incorrect!
int fahrenheit = (int) (Double.parseDouble(text.getText()) * 1.8 + 32);
label1.setText(fahrenheit + " Fahrenheit");
text.setText("");
text.requestFocus();
}
else {
label1.setText("No Celsius input");
text.requestFocus();
}
}
}
}
如果把if的条件判断改为 x != null 或者 x != "",都是错误的,但是用x.length()可以判断,那么为空时读取的值到底是多少呢?
x != "" 返回false.
x=="" 返回false