确定字符串是否是Java中的整数[重复]

本文探讨了在Java中判断字符串是否表示整数的多种方法,包括使用正则表达式、Integer.parseInt()和Integer.valueOf()等。通过实例演示了如何避免NumberFormatException,并提供了高效的解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本文翻译自:Determine if a String is an Integer in Java [duplicate]

This question already has an answer here: 这个问题已经在这里有了答案:

I'm trying to determine if a particular item in an Array of strings is an integer or not. 我正在尝试确定字符串数组中的特定项目是否为整数。

I am .split(" ")'ing an infix expression in String form, and then trying to split the resultant array into two arrays; .split(" ")'ingString形式插入一个中缀表达式,然后尝试将结果数组拆分为两个数组; one for integers, one for operators, whilst discarding parentheses, and other miscellaneous items. 一个用于整数,一个用于运算符,同时丢弃括号和其他杂项。 What would be the best way to accomplish this? 做到这一点的最佳方法是什么?

I thought I might be able to find a Integer.isInteger(String arg) method or something, but no such luck. 我以为我可以找到Integer.isInteger(String arg)方法或其他方法,但是没有这种运气。


#1楼

参考:https://stackoom.com/question/mP4l/确定字符串是否是Java中的整数-重复


#2楼

Or simply 或者简单地

mystring.matches("\\\\d+")

though it would return true for numbers larger than an int 尽管对于大于int的数字将返回true


#3楼

Using regular expression is better. 使用正则表达式更好。

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


-?     --> negative sign, could have none or one
\\d+   --> one or more digits

It is not good to use NumberFormatException here if you can use if-statement instead. 如果可以改为使用if-statement在此处使用NumberFormatException不好。


If you don't want leading zero's, you can just use the regular expression as follow: 如果您不想以零开头,则可以使用正则表达式,如下所示:

str.matches("-?(0|[1-9]\\d*)");

#4楼

public boolean isInt(String str){
    return (str.lastIndexOf("-") == 0 && !str.equals("-0")) ? str.substring(1).matches(
            "\\d+") : str.matches("\\d+");
}

#5楼

You want to use the Integer.parseInt(String) method. 您要使用Integer.parseInt(String)方法。

try{
  int num = Integer.parseInt(str);
  // is an integer!
} catch (NumberFormatException e) {
  // not an integer!
}

#6楼

You can use Integer.parseInt() or Integer.valueOf() to get the integer from the string, and catch the exception if it is not a parsable int. 您可以使用Integer.parseInt()Integer.valueOf()从字符串中获取整数,如果它不是可解析的int,则捕获该异常。 You want to be sure to catch the NumberFormatException it can throw. 您要确保捕获到它可能引发的NumberFormatException

It may be helpful to note that valueOf() will return an Integer object, not the primitive int. 注意valueOf()将返回一个Integer对象,而不是原始int可能会有所帮助。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值