热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

确定在Java中字符串是否是整数[复制]-DetermineifaStringisanIntegerinJava[duplicate]

Thisquestionalreadyhasananswerhere:这个问题已经有了答案:WhatsthebestwaytocheckifaS

This question already has an answer here:

这个问题已经有了答案:

  • What's the best way to check if a String represents an integer in Java? 34 answers
  • 检查字符串是否表示Java中的整数的最好方法是什么?34个答案

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; one for integers, one for operators, whilst discarding parentheses, and other miscellaneous items. What would be the best way to accomplish this?

我是。split(“”)将一个infix表达式用字符串形式表示,然后尝试将结果数组拆分为两个数组;一个用于整数,一个用于运算符,同时丢弃圆括号和其他杂项。最好的方法是什么?

I thought I might be able to find a Integer.isInteger(String arg) method or something, but no such luck.

我想我可以找到一个整数。isInteger(String arg)方法或什么的,但没有这样的运气。

9 个解决方案

#1


297  

The most naive way would be to iterate over the String and make sure all the elements are valid digits for the given radix. This is about as efficient as it could possibly get, since you must look at each element at least once. I suppose we could micro-optimize it based on the radix, but for all intents and purposes this is as good as you can expect to get.

最简单的方法是遍历字符串,并确保所有元素都是给定基数的有效数字。这是尽可能有效的,因为您必须至少查看每个元素一次。我想我们可以基于基数对它进行微优化,但是对于所有的意图和目的,这是你可以期望得到的。

public static boolean isInteger(String s) {
    return isInteger(s,10);
}

public static boolean isInteger(String s, int radix) {
    if(s.isEmpty()) return false;
    for(int i = 0; i 

Alternatively, you can rely on the Java library to have this. It's not exception based, and will catch just about every error condition you can think of. It will be a little more expensive (you have to create a Scanner object, which in a critically-tight loop you don't want to do. But it generally shouldn't be too much more expensive, so for day-to-day operations it should be pretty reliable.

或者,您可以依赖Java库来实现这一点。它并不是特例,它将捕获您所能想到的所有错误条件。它将会更贵一些(你必须创建一个扫描对象,在一个你不想做的临界循环中)。但它一般不应该太贵,所以对于日常运营来说,它应该是相当可靠的。

public static boolean isInteger(String s, int radix) {
    Scanner sc = new Scanner(s.trim());
    if(!sc.hasNextInt(radix)) return false;
    // we know it starts with a valid int, now make sure
    // there's nothing left!
    sc.nextInt(radix);
    return !sc.hasNext();
}

If best practices don't matter to you, or you want to troll the guy who does your code reviews, try this on for size:

如果最佳实践对您来说不重要,或者您想要对您进行代码评审的人,请尝试以下的大小:

public static boolean isInteger(String s) {
    try { 
        Integer.parseInt(s); 
    } catch(NumberFormatException e) { 
        return false; 
    } catch(NullPointerException e) {
        return false;
    }
    // only got here if we didn't return false
    return true;
}

#2


188  

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语句,那么在这里使用NumberFormatException是不好的。

#3


110  

Or you can enlist a little help from our good friends at Apache Commons : StringUtils.isNumeric(String str)

或者你也可以从我们在Apache Commons的好朋友那里得到一点帮助:StringUtils。isNumeric(String str)

#4


61  

Or simply

或者简单地

mystring.matches("\\d+")

mystring.matches(“\ \ d +”)

though it would return true for numbers larger than an int

虽然它会返回大于整数的数。

#5


43  

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


12  

As an alternative to trying to parse the string and catching NumberFormatException, you could use a regex; e.g.

作为尝试解析字符串和捕获NumberFormatException的替代方法,您可以使用regex;如。

if (Pattern.compile("-?[0-9]+").matches(str)) {
    // its an integer
}

This is likely to be faster, especially if you precompile and reuse the regex. However, the catch is that Integer.parseInt(str) will still fail if str represents a number that is outside range of legal int values.

这可能会更快,特别是如果您预编译和重用regex。但是,如果str表示一个超出合法int值范围的数字,则parseint (str)仍然会失败。

#7


8  

You can use Integer.parseInt(str) and catch the NumberFormatException if the string is not a valid integer, in the following fashion (as pointed out by all answers):

您可以使用Integer.parseInt(str)并捕获NumberFormatException,如果字符串不是一个有效整数,按照以下方式(所有答案都指出):

static boolean isInt(String s)
{
 try
  { int i = Integer.parseInt(s); return true; }

 catch(NumberFormatException er)
  { return false; }
}

However, note here that if the evaluated integer overflows, the same exception will be thrown. Your purpose was to find out whether or not, it was a valid integer. So its safer to make your own method to check for validity:

但是,请注意,如果评估的整数溢出,将抛出相同的异常。你的目的是找出它是否是一个有效的整数。因此,用你自己的方法来检查有效性更安全:

static boolean isInt(String s)  // assuming integer is in decimal number system
{
 for(int a=0;a

#8


2  

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. You want to be sure to catch the NumberFormatException it can throw.

您可以使用Integer.parseInt()或Integer.valueOf()来从字符串获取整数,如果它不是一个可解析的int,则捕获异常。

It may be helpful to note that valueOf() will return an Integer object, not the primitive int.

值得注意的是,valueOf()将返回一个整数对象,而不是原语int。

#9


-1  

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

推荐阅读
  • Python正则表达式学习记录及常用方法
    本文记录了学习Python正则表达式的过程,介绍了re模块的常用方法re.search,并解释了rawstring的作用。正则表达式是一种方便检查字符串匹配模式的工具,通过本文的学习可以掌握Python中使用正则表达式的基本方法。 ... [详细]
  • Google Play推出全新的应用内评价API,帮助开发者获取更多优质用户反馈。用户每天在Google Play上发表数百万条评论,这有助于开发者了解用户喜好和改进需求。开发者可以选择在适当的时间请求用户撰写评论,以获得全面而有用的反馈。全新应用内评价功能让用户无需返回应用详情页面即可发表评论,提升用户体验。 ... [详细]
  • 本文整理了Java中java.lang.NoSuchMethodError.getMessage()方法的一些代码示例,展示了NoSuchMethodErr ... [详细]
  • Nginx使用(server参数配置)
    本文介绍了Nginx的使用,重点讲解了server参数配置,包括端口号、主机名、根目录等内容。同时,还介绍了Nginx的反向代理功能。 ... [详细]
  • 本文介绍了设计师伊振华受邀参与沈阳市智慧城市运行管理中心项目的整体设计,并以数字赋能和创新驱动高质量发展的理念,建设了集成、智慧、高效的一体化城市综合管理平台,促进了城市的数字化转型。该中心被称为当代城市的智能心脏,为沈阳市的智慧城市建设做出了重要贡献。 ... [详细]
  • CSS3选择器的使用方法详解,提高Web开发效率和精准度
    本文详细介绍了CSS3新增的选择器方法,包括属性选择器的使用。通过CSS3选择器,可以提高Web开发的效率和精准度,使得查找元素更加方便和快捷。同时,本文还对属性选择器的各种用法进行了详细解释,并给出了相应的代码示例。通过学习本文,读者可以更好地掌握CSS3选择器的使用方法,提升自己的Web开发能力。 ... [详细]
  • baresip android编译、运行教程1语音通话
    本文介绍了如何在安卓平台上编译和运行baresip android,包括下载相关的sdk和ndk,修改ndk路径和输出目录,以及创建一个c++的安卓工程并将目录考到cpp下。详细步骤可参考给出的链接和文档。 ... [详细]
  • 推荐系统遇上深度学习(十七)详解推荐系统中的常用评测指标
    原创:石晓文小小挖掘机2018-06-18笔者是一个痴迷于挖掘数据中的价值的学习人,希望在平日的工作学习中,挖掘数据的价值, ... [详细]
  • 拥抱Android Design Support Library新变化(导航视图、悬浮ActionBar)
    转载请注明明桑AndroidAndroid5.0Loollipop作为Android最重要的版本之一,为我们带来了全新的界面风格和设计语言。看起来很受欢迎࿰ ... [详细]
  • 自动轮播,反转播放的ViewPagerAdapter的使用方法和效果展示
    本文介绍了如何使用自动轮播、反转播放的ViewPagerAdapter,并展示了其效果。该ViewPagerAdapter支持无限循环、触摸暂停、切换缩放等功能。同时提供了使用GIF.gif的示例和github地址。通过LoopFragmentPagerAdapter类的getActualCount、getActualItem和getActualPagerTitle方法可以实现自定义的循环效果和标题展示。 ... [详细]
  • CF:3D City Model(小思维)问题解析和代码实现
    本文通过解析CF:3D City Model问题,介绍了问题的背景和要求,并给出了相应的代码实现。该问题涉及到在一个矩形的网格上建造城市的情景,每个网格单元可以作为建筑的基础,建筑由多个立方体叠加而成。文章详细讲解了问题的解决思路,并给出了相应的代码实现供读者参考。 ... [详细]
  • FeatureRequestIsyourfeaturerequestrelatedtoaproblem?Please ... [详细]
  • 本文详细介绍了Android中的坐标系以及与View相关的方法。首先介绍了Android坐标系和视图坐标系的概念,并通过图示进行了解释。接着提到了View的大小可以超过手机屏幕,并且只有在手机屏幕内才能看到。最后,作者表示将在后续文章中继续探讨与View相关的内容。 ... [详细]
  • 本文概述了JNI的原理以及常用方法。JNI提供了一种Java字节码调用C/C++的解决方案,但引用类型不能直接在Native层使用,需要进行类型转化。多维数组(包括二维数组)都是引用类型,需要使用jobjectArray类型来存取其值。此外,由于Java支持函数重载,根据函数名无法找到对应的JNI函数,因此介绍了JNI函数签名信息的解决方案。 ... [详细]
  • 本文整理了Java中org.gwtbootstrap3.client.ui.Icon.addDomHandler()方法的一些代码示例,展示了Icon.ad ... [详细]
author-avatar
牛牛的牛66_674
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有