Sunday, 15 November 2015

How to convert the given string to number in Java?


 In this tutorial, i am going to explain how to convert a given String to Integer in Java with and without using predefined methods of Java.

Input: "1234" Output: 1234
Input: "abc" Output: an Exception.

Problem:

    How to convert the given string to number in Java?

Method 1 - Using predefined method of Integer Class:

use ParseInt() method of Integer class to convert given String to Integer. The code snippet is showed below.

private static int convertToInteger2(String aString) {
        
        return Integer.parseInt(aString);
    
 }
    
Method 2 - Without using predefined methods:

In this approach, we are not going to use any predefined methods for conversion. we are going to write our own algorithm for this purpose.

The algorithm is simple, we are going to iterate through each character of the give String and convert it to digit. we maintain a temporary integer for calculating the result. Below is the step by step procedure.

Algorithm:

    1. Initialize a temporary integer to 0. which represents the result. int num = 0;
    2. Iterate through each character of the given string. char aChar;
    for(int i = 0; i < aString.length(); i++) {     aChar = aString.charAt(i);
    3. Check if the character is digit or not. If it is a digit, then convert it to integer, else throw an exception. Character.isDigit(aChar);
    4. You can convert the character to integer, by subtracting '0' from it. aChar - '0'; // converts the character to integer
    5. For each converted integer, multiply temporary integer with 10 and add the converted integer to it. num = (num * 10) + (aChar - '0');
    6. Finally return the result.
   
The complete program is below.
package fundamentals;

public class StringToNumber {

    public static void main(String[] args) {

        System.out.println(convertToInteger("12345.56"));

    }


    private static int convertToInteger(String aString) {

        int num = 0;

        char aChar;

        

        for(int i = 0; i < aString.length(); i++) {

            aChar = aString.charAt(i);

            if(Character.isDigit(aChar)) {

                num = (num*10)+(aChar-'0');

            } else {

                throw new NumberFormatException(aChar +" is not a digit at pos" + (i+1));

            }

        }

        return num;

    }

    private static int convertToInteger2(String aString) {
        
        return Integer.parseInt(aString);
    } 

}

0 comments:

Post a Comment

Note: only a member of this blog may post a comment.