Sunday, August 23, 2015

Write a Java Program to convert String value into Integer value with out using parseInt() method.


In this post, we are going to learn how to convert string value into integer value with out using the parseInt() method.

package com.ranga;

/**
*
* This class is used to convert the String value into Integer.
* @author Ranga Reddy
* @version 1.0
*
*/

public class StringToInteger {

public static void main(String[] args) {
String string = "123456";
System.out.println("String value: "+ string);
int integerValue = convertStringToInteger(string);
System.out.println("Integer value: "+ integerValue);
}

/**
* Used to convert the String to Integer.
* @param str - the value of a string value
* @return the integer value.
*/

public static int convertStringToInteger( String str ) {
if(str == null)
throw new NullPointerException("Value is "+str);

int i = 0, intValue = 0;
boolean isNegativeValue = false;
int strLength = str.length();
// checking the first character is negative or not. if it is negative then i start with 1.
if( str.charAt(0) == '-' ){
isNegativeValue = true;
i = 1;
}

for(;i<strLength; i++) {
int value = str.charAt(i) - '0';
if( value > -1 && value < 10 ) {
intValue *= 10;
intValue += value;
} else {
throw new NumberFormatException("Invalid integer string. Value is "+str);
}
}

// if value is negative then adding the prefix is -
if( isNegativeValue ) {
intValue = -intValue;
}
return intValue;
}
}

Input 1: 
String string = null;
Output 1:
Exception in thread "main" java.lang.NumberFormatException: null value can't be convert into integer.
Explanation: If the string value is null then throwing the NumberFormatException.

Input 2:
String  string = "143";
Output 1:
143
Explanation: 
Initial values of 
int i = 0;
int intValue = 0;
boolean isNegativeValue = false;
int strLength = str.length() = 3;

Then checking the string 0th position value will be -ve or not because number can be positive or negative.
if(str.charAt(0) == '-') {

}

If it is true then number start position will be 1 on words. so now i value will be. And also make isNegativeValue value will be true. In the above case 0th position is not negative value. so i value start with 0 only.
then get the each position value and multiply with 10 and add into the end of integer value.

i =0
value = str.charAt(i) - '0' = str.charAt(0) - '0' = 49 - 48 = 1
intValue = 0 * 10 = 10
intValue = intValue +  value = 0 + 1 = 1

Note: str.charAt(1) returns the ASCII value of 1. ASCII value of 1 is 49 and then substracting the ASCII value of 0 is 48

i = 1
value = str.charAt(1) = 52 - 48 = 4
intValue = 1 * 10 = 10
intValue = 10 + 4 = 14

i = 2
value = str.charAt(2) = 51 - 48 = 3
intValue = 14 * 10 = 140
intValue = 140 + 3 = 143

Note: value should be always between 0 to 9 only. If it not then throwing the NumberFormatException








0 comments: