Java 如何检查字符串是否为有效整数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21803908/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check if a string is a valid integer?
提问by Dannyl
I have:
我有:
op1 = Integer.parseInt(jTextField1.getText());
op2 = Integer.parseInt(jTextField2.getText());
However, I want to check first whether the text fields' values can be assigned to integer variables. How do I do that?
但是,我想首先检查文本字段的值是否可以分配给整数变量。我怎么做?
I've been going through this for a long time, so, if this was already asked here, forgive me
我已经经历了很长时间,所以,如果这里已经问过这个问题,请原谅我
采纳答案by Warlord
You can't do if (int i = 0)
, because assignment returns the assigned value (in this case 0
) and if
expects an expression that evaluates either to true
, or false
.
您不能这样做if (int i = 0)
,因为赋值返回分配的值(在本例中为0
)并if
期望计算结果为true
或的表达式false
。
On the other hand, if your goal is to check, whether jTextField.getText()
returns a numeric value, that can be parsed to int
, you can attempt to do the parsing and if the value is not suitable, NumberFormatException
will be raised, to let you know.
另一方面,如果您的目标是检查是否jTextField.getText()
返回一个可以解析为的数值int
,您可以尝试进行解析,如果该值不合适,NumberFormatException
将被提出,让您知道。
try {
op1 = Integer.parseInt(jTextField1.getText());
} catch (NumberFormatException e) {
System.out.println("Wrong number");
op1 = 0;
}
回答by Smutje
Basically, you have to decide to check if a given string is a valid integer or you simply assume a given string is a valid integer and an exception can occur at parsing.
基本上,您必须决定检查给定字符串是否是有效整数,或者您只是假设给定字符串是有效整数,并且在解析时可能会发生异常。
回答by xp500
parseInt throws NumberFormatException if it cannot convert the String to an int. So you should surround the parseInt calls with a try catch block and catch that exception.
如果 parseInt 无法将 String 转换为 int,则会抛出 NumberFormatException。所以你应该用 try catch 块包围 parseInt 调用并捕获该异常。
回答by Niroshan Abeywickrama
This works for me. Simply to identify whether a String is a primitive or a number.
这对我有用。简单地识别一个字符串是原始值还是数字。
private boolean isPrimitive(String value){
boolean status=true;
if(value.length()<1)
return false;
for(int i = 0;i<value.length();i++){
char c=value.charAt(i);
if(Character.isDigit(c) || c=='.'){
}else{
status=false;
break;
}
}
return status;
}