String conversion to integer format and vice versa in Java

PsuedoCode

Start number at 0
If the first character is ‘-‘
Set the negative flag
Start scanning with the next character
For each character in the string
Multiply number by 10
Add (digit character – ‘0’) to number
If negative flag set
Negate number
Return number

/*The following program reads a number in String format and displays it in a number format @author Ashish Dutt  */
package String;
import java.util.Scanner;
public class StringToInteger {

  public static int strToInt( String str ){
    int i = 0, num = 0;
    boolean isNeg = false;
    int len = str.length();

    if( str.charAt(0) == '-' ){
        isNeg = true;
        i = 1;
    }
    while( i < len ){
        num *= 10;
        num += ( str.charAt(i++) - '0' );
    }
    if( isNeg )
        num = -num;
    return num;
}
    public static void main(String[] args) {
        String s;
        Scanner input=new Scanner(System.in);
        System.out.println("Enter a number: ");
        s=input.nextLine();
        System.out.println("Equivalent Conversion to Integer format is= "+strToInt(s));

    }}
Advertisements

One thought on “String conversion to integer format and vice versa in Java

Comments are closed.