[英]How to check if a string is an int
Ok guys, so I basically made a GUI Java program, a basic one. 好的,所以我基本上制作了一个GUI Java程序,一个基本的程序。 Just adds/subs/divides orr multiplies numbers that are in the textfields, nothing big as I have only started learning Java. 只需对文本字段中的数字进行加/减/除运算即可,这没什么大不了的,因为我才刚刚开始学习Java。 It works but there are some bugs, such as when you execute it and if you click on one of the radiobutton without entering a number in the textfields then the programme will not work. 它可以工作,但是存在一些错误,例如,当您执行它时,并且如果您在其中一个单选按钮上单击而不在文本字段中输入数字,则该程序将无法工作。 How can I check whether the user entered an integer whenenver the user clicks on the radiobuttons? 每次单击单选按钮时,如何检查用户是否输入了整数? Heres the code: 这是代码:
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);
}
}
}
}
It depends what you mean by integer, but if you just want to check if string contains only digits and optionally -
at start you can check it using regex like 它取决于整数的含义,但是,如果您只想检查字符串是否仅包含数字,并且可以选择-
在开始时,可以使用regex进行检查,例如
yourString.matches("-?\\d+");
Note that this will not check range of number. 请注意,这不会检查数字范围。
Simply do: 只需做:
String text = num1.getText();
try {
Integer x = Integer.parseInt(text);
} catch (NumberFormatException) {
System.out.println(text + " cannot be converted to integer");
}
If the String can't be parsed to Integer
, a NumberFormatException
will be thrown. 如果无法将String解析为Integer
,则将引发NumberFormatException
。
You should check, if the TextField is empty, and you should add some error handling to the integer parsing, like: 您应该检查TextField是否为空,并且应该在整数解析中添加一些错误处理,例如:
try {
x = Integer.parseInt(num1.getText())>
catch (NumberFormatException ex) {
//error handling
}
Convert to char[]
using toCharArray()
使用toCharArray()
转换为char[]
Then loop through and check if each character isDigit()
然后循环遍历并检查每个字符是否为isDigit()
edit* As others have said, catching exceptions is a much better way of handling this issue 编辑*正如其他人所说,捕获异常是处理此问题的更好方法
When Integer.parseInt(...)
is given something it cannot parse, it throws a NumberFormatException
. 当给Integer.parseInt(...)
某些无法解析的内容时,它将引发NumberFormatException
。 You should wrap your parseInt(...)
calls in a try/catch block and handle the situation appropriately: 您应将parseInt(...)
调用包装在try / catch块中,并适当处理这种情况:
try {
x = Integer.parseInt(num1.getText());
} catch (NumberFormatException nfe) {
// do something about broken data
}
It woul dbe convenient to use a seperate method to do all the parsing and handlng to reduce the amount of code duplication 使用单独的方法进行所有解析和处理以减少代码重复的数量将很方便
You can use a function like this: 您可以使用如下功能:
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.