0

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!

4
  • 3
    isValidNumber() is wrong, because if the first number is a digit, then it returns true, even if the rest are not digits. Instead do c < '0' || c > '9' and switch the places of return true and return false. Commented Dec 10, 2016 at 19:04
  • Oh thats cool, thanks! But can you also help me to get negativ numbers working? I have no idea how to make a exception for the char "-" Commented Dec 10, 2016 at 19:08
  • Negative numbers don't work either, because '-' is not an integer. You need to do a new section in isValidNumber() for if(str.charAt(0) == '-'). Then instead of i = 0 in your for loop, start with i = 1. Commented Dec 10, 2016 at 19:09
  • you may ant ti use a regular exprression rather than iterating over the (possible) digits yourself. Refer Java API docs.oracle.com/javase/8/docs/api/java/lang/… docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html Commented Dec 10, 2016 at 19:10

3 Answers 3

1

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
Sign up to request clarification or add additional context in comments.

Comments

0

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

1 Comment

He's creating his own parseInt() method, though. Using the one in the Java library is probably not an option.
0

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

4 Comments

Could Character.isDigit be used here?
Absolutely. I think the OP wants to also include negative numbers as well.
Your latest edit ruins everything, because now 5-6+33- returns true, does it not?
@Gendarme, no since the charAt(1) == '-' and the if (i > 0) will kick in, thus returning a false.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.