Thứ Sáu, 29 tháng 8, 2014

Converting a String to int with out using parseInt() in java

Hi Guys ,welcome

         You might have performed converting a string to an int when you are reading data from standard inputstreams(because it treats input data as string format).

for example see the below snippet

Scanner sc=new Scanner(System.in);//sc is pointing to inputstream as in string format.
int data=sc.nextInt();

if you are readed data using BufferedReader,then code snippet will be like

InputStreamReader in=new InputStreamReader(System.in);
BufferedReader br new BufferedReader(in);
int data=Integer.parseInt(br.readLine());

Now our aim is to perform same convertion with out using above methods.

preconditions are :
1.check if number is positive or negitive (do this by using charAt() method).
2.if number is negitive return negitive number

logic:
         number="12345"; //is a string number
         if(number.chatAt(0)=='-')//it is a negitive number so return negitive number
         return =number;

Solution:

                package logics;

public class check {
    public static void main(String []args)
    {

        String data="12345";
        System.out.println("String data before converting to int "+data);
        int res=toInt(data);
        System.out.println("in integer format \t"+res);
       
    }
    public static int toInt(String data)
    {
        int index,start=1,len=data.length(),intdata=1;
        boolean isnegitive=false;
        if(data.charAt(0)=='-')
        {
            isnegitive=true;
        }
        while(start<len)
        {
            intdata*=10;
            intdata+=(data.charAt(start++)-'0');
           
        }
        if(isnegitive)
            intdata=-intdata;
        return intdata;
       

    }
}


output:

------------------------------------------
String data before converting to int 12345
in integer format     12345
 


Không có nhận xét nào:

Đăng nhận xét