Number Format Exception - converting with parseInt

354 views Asked by At

I am working at converting string number into binary. But Eclipse throws a NumberFormatException. Can I ask you, to look at my code? I have no idea what is wrong..

public float liczbaF(String lancuch){
    float array [] = new float [31];
    float liczba;
    double mantysa;
    int znak;
    long cecha;
    char element[] = new char[22];
    String temp="";


    if (lancuch.charAt(0)=='1')
        znak=-1;
    else
        znak=1;


    for(int i=1;i<8;i++)
        {
        element[i-1] = lancuch.charAt(i);
        }

    temp=String.valueOf(element);
    System.out.println(temp);
    cecha=Integer.parseInt(temp,10);
    cecha=cecha-127;
    System.out.println(cecha);

    for(int i=31;i>9;i--)
    {
    element[31-i] = lancuch.charAt(i);
    }
    temp=String.valueOf(element);
    mantysa=(((Integer.parseInt(temp,10))/(pow(2,22)))+1);
    liczba=(float)(mantysa*pow(2,cecha));
    return liczba;
}

It throws:

Exception in thread "main" java.lang.NumberFormatException: For input string: "1001101
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at Konwersja.liczbaF(Konwersja.java:30)
at Main.main(Main.java:10)

I will be grateful for any help. Thank you

2

There are 2 answers

0
JP Moresmau On

Your element array is 22 long:

 char element[] = new char[22];

but you only fill in the first 7 elements:

 for(int i=1;i<8;i++)
    {
    element[i-1] = lancuch.charAt(i);
    }

So there are null characters at the end of the string, which make it unparseable as an integer. This works better:

temp=String.valueOf(element,0,7);

I would recommend using a StringBuilder to add characters to a String, not a char array.

0
Gobinath On

The reason for NumberFormatException is the hidden characters of element array. element array has a length of 22 but only filled by first few characters. So the rest are '\u0000'. An easy solution is: modify this line:

temp=String.valueOf(element);

to:

temp=String.valueOf(element).trim();