当前位置: 代码迷 >> J2SE >> 如何判断读入的是字符串还是数字?
  详细解决方案

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

热度:116   发布时间:2016-04-24 02:30:04.0
怎么判断读入的是字符串还是数字??
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;}    }}
------解决方案--------------------
通过正则表达式
  相关解决方案