尝试确定字符串是否为整数 [英] Trying to determine if a string is an integer

查看:99
本文介绍了尝试确定字符串是否为整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说明: 给定字符串,请确定它是否为整数.例如 字符串"123"是整数,但字符串"hello"不是整数.

Instructions: Given a string, determine if it is an integer. For example the string "123" is an integer, but the string "hello" is not.

如果字符串中的所有字符均为数字,则为整数.

It is an integer if all of the characters in the string are digits.

如果是整数,则返回true;否则,则返回false.

Return true if it is an integer, or false if it is not.

提示:有一个Character.isDigit()方法,该方法以char作为参数. 并返回一个布尔值.

Hint: There is a method Character.isDigit() that takes a char as an argument and returns a boolean value.

到目前为止我所拥有的:

What I have so Far:

public boolean isInteger(String str) {
    if(Character.isDigit(str.charAt(0)) == 0) {
        return false;
    }
    for (int i = 0; i < str.length(); i++) {
        if(Character.isDigit(str.charAt(i))) {
            break;
        } else {
            return false;
        }
    }
    return true;
}

我在返回字符串"101"的布尔值而根本没有任何字符串(")时遇到问题

I'm having an issue with returning a boolean value for the string "101" and no string at all (" ")

推荐答案

您可以使用正则表达式.

You could use a regular expression.

return str.matches("\\d+");

但是,

不适用于负数.

won't work for negative numbers, though.

您还可以使用Integer.parseInt并捕获NumberFormatException并相应地返回true/false.

You could also use Integer.parseInt and catch the NumberFormatException and return true/false accordingly.

或者,您不应破坏找到的第一个数字,因为您需要检查所有字符,只是直到找到一个不是的数字.同样,这不会捕获负数

Or, you should not break the first digit you find, as you need to check all characters, only until you find one that is not a digit. Again, this does not capture negative numbers

public boolean isInteger(String str) {
    if(str == null || str.trim().isEmpty()) {
        return false;
    }
    for (int i = 0; i < str.length(); i++) {
        if(!Character.isDigit(str.charAt(i))) {
            return false;
        } 
    }
    return true;
}

就个人而言,选项2是最好的,但是您的说明似乎暗示您需要遍历字符值

Personally, option 2 is the best, but your instructions seem to imply that you need to iterate over character values

这篇关于尝试确定字符串是否为整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆