如何检查字符串是否为int

时间:2013-10-19 17:03:18

标签: java user-interface

好的,所以我基本上制作了一个基本的GUI Java程序。只是添加/ subs / divides orr乘以文本字段中的数字,没有什么大的,因为我只是开始学习Java。它有效,但有一些错误,例如当你执行它时,如果你单击其中一个radiobutton而没有在文本字段中输入数字,那么程序将无法工作。如何在用户点击radiobuttons时检查用户是否输入了整数? 下面是代码:

import java.awt.event.*;
import java.text.NumberFormat;
import javax.swing.*;
import java.awt.*;


public class GUI extends JFrame{

    Button button1;
    TextField num1;
    TextField num2;
    JRadioButton add,sub,mul,div;
    boolean isnumber = false;


    int x, y, sum;

    public static void main(String[] args){


        new GUI();

    }

    public GUI(){

        thehandler handle = new thehandler();

        JPanel panel = new JPanel();
        this.setLocationRelativeTo(null);
        this.setVisible(true);
        this.setSize(800, 70);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setTitle("Calc");
        this.add(panel);



        button1 = new Button("Calculate");
        button1.addActionListener(handle);
        panel.add(button1);

        num1 = new TextField("Enter a number here");
        num1.addActionListener(handle);
        num2 = new TextField("Enter a number here");
        num2.addActionListener(handle);
        panel.add(num1);
        panel.add(num2);

        add = new JRadioButton("Add");
        add.addActionListener(handle);
        sub = new JRadioButton("Subtract");
        sub.addActionListener(handle);
        mul = new JRadioButton("Multiply");
        mul.addActionListener(handle);
        div = new JRadioButton("Divide");
        div.addActionListener(handle);

        ButtonGroup operation = new ButtonGroup();
        operation.add(add);
        operation.add(sub);
        operation.add(div);
        operation.add(mul);

        panel.add(add);
        panel.add(sub);
        panel.add(mul);
        panel.add(div);




    }

    private class thehandler implements ActionListener{

        @Override
        public void actionPerformed(ActionEvent e) {


            if(e.getSource() == add){
                sum = x + y;
                x = Integer.parseInt(num1.getText());
                y = Integer.parseInt(num2.getText());           
            }
            if(e.getSource() == sub){
                sum = x - y;
                x = Integer.parseInt(num1.getText());
                y = Integer.parseInt(num2.getText());
            }
            if(e.getSource() == mul){
                sum = x * y;
                x = Integer.parseInt(num1.getText());
                y = Integer.parseInt(num2.getText());
            }
            if(e.getSource() == div){
                sum = x/y;
                x = Integer.parseInt(num1.getText());
                y = Integer.parseInt(num2.getText());
            }
            if(e.getSource() == button1){

                JOptionPane.showMessageDialog(null, "The sum of the desired calculation is... " + sum);
            }

        }

    }



}

6 个答案:

答案 0 :(得分:4)

这取决于你所说的整数,但是如果你只是想检查字符串是否只包含数字而且可以选择-,你可以使用正则表达式检查

yourString.matches("-?\\d+");

请注意,这不会检查数字范围。

答案 1 :(得分:3)

简单地说:

String text = num1.getText();
try {
   Integer x = Integer.parseInt(text);
} catch (NumberFormatException) {
   System.out.println(text + " cannot be converted to integer");
}

如果无法将字符串解析为Integer,则会抛出NumberFormatException

答案 2 :(得分:1)

如果TextField为空,您应该检查,并且应该对整数解析添加一些错误处理,例如:

try {
    x = Integer.parseInt(num1.getText())>
catch (NumberFormatException ex) {
    //error handling
}

答案 3 :(得分:0)

使用char[]

转换为toCharArray()

然后循环并检查每个字符isDigit()

编辑* 正如其他人所说,捕获异常是解决此问题的更好方法

答案 4 :(得分:0)

Integer.parseInt(...)被赋予无法解析的内容时,它会抛出NumberFormatException。您应该将parseInt(...)调用包装在try / catch块中并适当地处理这种情况:

try {
    x = Integer.parseInt(num1.getText());
} catch (NumberFormatException nfe) {
    // do something about broken data
}

使用单独的方法进行所有解析和处理以减少代码重复量是方便的

答案 5 :(得分:0)

您可以使用以下功能:

boolean isInt(String str) {
     for (int i = 0; i < str.length(); i++) {
         char c = str.charAt(i);
         if (!Character.isDigit(c)) {
            return false;
         }
     }
     return true;
}