Sunday, 28 February 2016

How to Convert String to Int without using Integer.parseInt() method: Code With Example

As integer can be positive and negative, here two cases arise.

Use cases#
Case#1: If string is positive
If user inputs  "12312", then it should give output 12312 as an int number

Case#2: If string is negative
If user inputs "-47939", then it should give output -47939 as an int number.

Case#3: If string contains alphabetic character like "12ab6", it should print an error.

Approach#
We will traverse the character array as we know String is the array of character.

Step#1: int_value = 0;

Step#2: Traverse the Character array from right to left.

Step#3: Find the place_value of the Character because the ASCII value is different of character to string.

Step#4: Multiplying the place value by 10 each time and add to sum.
              int_value = int_value + place_value * 10;


import java.text.ParseException;
public class IntegerParser {

     public static int parseInt(String str) throws ParseException {
           int i = 0, number = 0;
           boolean isNegative = false;
           char[] value = str.toCharArray();
           if(value[0] == '-') {
                isNegative = true;
                i = 1;
           }

           while(i < value.length) {
                char ch = value[i++];
                int place_value = ch - '0';
                if(place_value>=0 && place_value<=9) {
                     number *= 10;
                     number += (ch - '0');
                } else {
                    System.out.println("Wrong input format!!");
                    throw newParseException("String to int parse",-1);
                }
           }
           if(isNegative) {
                number = -number;
           }
           return number;
     }


     public static void main (String args[]) throws ParseException {
           String  convertingString="1243";
           int integer = parseInt(convertingString);
           System.out.println(integer);

           convertingString="-1243";
           integer = parseInt(convertingString);
           System.out.println(integer);
          
           convertingString="-12a43";
           integer = parseInt(convertingString);
           System.out.println(integer);

     }
}

Output:
1243
-1243
Wrong input format!!
Exception in thread "main" java.text.ParseException: String to int parse
     at IntegerParser.parseInt(IntegerParser.java:39)
     at IntegerParser.main(IntegerParser.java:17)



For suggestions/doubts, please put your comments.

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...