使用if语句测试JTextField是否为整数 [英] Using an if statement to test if JTextField is an integer

查看:256
本文介绍了使用if语句测试JTextField是否为整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望我的程序能够判断我的两个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是否为整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆