简体   繁体   English

检查输入字符串为int

[英]Check input string to int

I have this method: 我有这种方法:

public static int parseInt(String str) {
    if (isValidNumber(str)) {
        int sum = 0;
        int position = 1;
        for (int i = str.length() - 1; i >= 0; i--) {
            int number = str.charAt(i) - '0';
            sum += number * position;
            position = position * 10;
        }
        return sum;
    }
    return -1;
}

which converts a string into a integer. 将字符串转换为整数。 And as you can see it is (at the moment) in a if-statement with a method which checks if the input is a valid input for my purpose: 正如您所看到的(当前),它处于if语句中,该方法使用一种检查输入是否对我而言有效的输入:

public static boolean isValidNumber(String str) {
    for (int i = 0; i < str.length(); i++) {
        char c = str.charAt(i);
        if(c >= '0' && c <= '9'){
            return true;
        }
    }
    return false;
}

I want the string to be number only (negative and positive) no other is allowed. 我希望字符串仅是数字(负数和正数),不允许其他数字。 At that time a string ie 1a1a will be converted to a integer which it shouldn't whereas -1 will not be converted. 那时,一个字符串(即1a1a将被转换为它不应该转换的整数,而-1将不被转换。 I think you guys understand what I mean. 我想你们明白我的意思。 I don't know how to do that. 我不知道该怎么做。

Please help! 请帮忙!

Try this: 尝试这个:

CODE: 码:

public class validNumbers {

    public static void main(String[] args) {

        System.out.println(parseInt("345"));
        System.out.println(parseInt("-345"));
        System.out.println(parseInt("a-345"));
        System.out.println(parseInt("1a5b"));
    }

    public static int parseInt(String str) {
        String numberWithoutSign = removeSign(str);
        if (isValidNumber(numberWithoutSign)) {
            int sum = 0;
            int position = 1;
            for (int i = numberWithoutSign.length() - 1; i >= 0; i--) {
                int number = numberWithoutSign.charAt(i) - '0';
                sum += number * position;
                position = position * 10;
            }
            if(isNegative(str)){
                return -(sum);
            }else{
                return sum;
            }
        }
        return -1;
    }

    /**
     * Removes sign in number if exists
     */
    public static String removeSign(String number){
        if(number.charAt(0) == '+' || number.charAt(0) == '-'){
            return number.substring(1);
        }else{
            return number;
        }
    }
    /**
     * Determines if a number is valid
     */
    public static boolean isValidNumber(String number) {
        for (int i = 0; i < number.length(); i++) {
            char c = number.charAt(i);
            if(c >= '0' && c <= '9'){
                continue;
            }else{
                return false;
            }
        }
        return true;
    }

    /**
     * Determines if a number is negative or not
     */
    public static boolean isNegative(String number){
        if(number.charAt(0) == '-'){
            return true;
        }else{
            return false;
        }
    }

}

OUTPUT: 输出:

345
-345
-1
-1

To check if a string is a real number you can use a method like this: 要检查字符串是否为实数,可以使用如下方法:

    public static boolean isInteger(String str) {
        try {
            Integer.parseInt(str);
            return true;
        } catch (NumberFormatException nfe) {}
        return false;
    }

The problem is with your function isValidNumber . 问题出在你的函数isValidNumber It should return a false on first occurrence of a non numeric value, as follows: 第一次出现非数字值时,应返回false,如下所示:

public static boolean isValidNumber(String str) {
    for (int i = 0; i < str.length(); i++) {
        char c = str.charAt(i);
        if(!(c >= '0' && c <= '9')){
            if (i > 0) {
                return false;
            }

            //This will only be invoked when `i == 0` (or less, which is impossible in this for loop), so I don't need to explicitly specify it here, as I have checked for `i > 0` in the above code...    
            if (c != '-' && c != '+') {
                return false;
            }
        }
    }

    return true;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM