问题描述
我希望我的程序能够判断我的两个JTextFields中的内容是整数还是字符串。
I want my program to be able to tell if what is inside my two JTextFields is an integer or a String.
代码
public void actionPerformed(ActionEvent e){
if(inputH.getText().equals(" Set Height ") ||
inputW.getText().equals(" Set Width ")){
JOptionPane.showMessageDialog(frame,
"Change Height And Width To A Number.",
"Change Height To A Number",
JOptionPane.ERROR_MESSAGE);
}
}
});
此if语句测试JTextField中的内容是否为Set Height
或设置宽度
但是我想让他们测试一下这些是什么,我该怎么做?
This if statement tests if what is in the JTextField is " Set Height "
or " Set Width "
but i want them to test if what is in them is a number, how would I do that?
我无法找出 Integer.ParseInt
。请帮助。
推荐答案
不确定代码中的确切位置,但您可以使用此方法确定是否String是一个整数:
Not sure exactly where in your code the test is being performed, but you can use this method to determine if a String is an integer:
public static boolean isInteger(String s) {
try {
Integer.parseInt(s);
} catch(NumberFormatException e) {
return false;
}
// if exception isn't thrown, then it is an integer
return true;
}
较便宜的无异常的方式,假设您的代码不需要抛出例外:
Less expensive none exception based way, assuming your code does not need to throw an exception:
public static boolean isInt(String s){
for(int i = 0; i < s.length(); i++){
if(!Character.isDigit(s.charAt(i))){
return false;
}
}
return true;
}
这篇关于使用if语句测试JTextField是否为整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!