首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > J2SE开发 >

如何判断读入的是字符串还是数字?

2012-02-25 
怎么判断读入的是字符串还是数字??button1.addActionListener(new ActionListener(){@Overridepublic void

怎么判断读入的是字符串还是数字??
button1.addActionListener(new ActionListener()
{

@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
if(Integer.parseInt(field.getText())<=100&&Integer.parseInt(field.getText())>=0)
lider.setValue (Integer.parseInt(field.getText()));

else

for(int i=0;i<field.getText().length();i++)
if(Character.isLetter(field.getText().charAt(i))==true)
JOptionPane.showMessageDialog(frame,"请输入0——100之间的数","错误信息",JOptionPane.ERROR_MESSAGE, null);

//判断读入的是否为非法字符,若为字符串,弹出错误对话框。。
}

});


没办法实现要求啊。。。。。

[解决办法]
有上下限的使用 JSpinner 获取用户输入。


Java code
class IntegerOnlyDocument extends PlainDocument {    @Override public void insertString(int offset, String str,AttributeSet a)                  throws BadLocationException {        if(str.matches("[0-9]+")){ super.insertString(offset,str,a);}        else {return;}    }}
[解决办法]
通过正则表达式

热点排行