ethanqt
ethanqt

Reputation: 63

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:

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 i.e 1a1a will be converted to a integer which it shouldn't whereas -1 will not be converted. I think you guys understand what I mean. I don't know how to do that.

Please help!

Upvotes: 0

Views: 264

Answers (3)

Buhake Sindi
Buhake Sindi

Reputation: 89169

The problem is with your function isValidNumber. It should return a false on first occurrence of a non numeric value, as follows:

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;
}

Upvotes: 0

Dani
Dani

Reputation: 2036

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

Upvotes: 1

daN
daN

Reputation: 101

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;
    }

Upvotes: 0

Related Questions