class PressBPN implements ActionListener {
public void actionPerformed(ActionEvent e) {
String text = tf.getText();
if (text != "") {
if(text.charAt(0) == '-')
tf.setText(text.substring(1));
else if(text.charAt(0) >= '0' && text.charAt(0) <= '9')
tf.setText("-"+text.substring(0));
else if(text.charAt(0) == '.')
tf.setText("-0"+text.substring(0));
}
}
}我自己写了个计算器,想在里面加一个正负转换的按钮,于是就在网上找,找到了上面这段代码。不过我看得似懂非懂。在JDK里面也没查到相关的信息。
麻烦知道的高手能帮我解释下这段代码一些方法我都不知道怎么使用的。。
public void actionPerformed(ActionEvent e) {
String text = tf.getText();
if (text != "") {
if(text.charAt(0) == '-')
tf.setText(text.substring(1));
else if(text.charAt(0) >= '0' && text.charAt(0) <= '9')
tf.setText("-"+text.substring(0));
else if(text.charAt(0) == '.')
tf.setText("-0"+text.substring(0));
}
}
}我自己写了个计算器,想在里面加一个正负转换的按钮,于是就在网上找,找到了上面这段代码。不过我看得似懂非懂。在JDK里面也没查到相关的信息。
麻烦知道的高手能帮我解释下这段代码一些方法我都不知道怎么使用的。。
先获得当前值,判断其是否为空,不是空再截取字符串的第一个字符,然后继续判断,有负号就去掉负号,没有就加上负号