Question

Ok, so I'm working on a method that is supposed to combine a set of binary numbers. For some reason I'm getting an exception on it. The method works when the numberOfBits is 4, but it gives an error when I move up to 7. I'm not exactly sure why it's doing this and nothing so far has fixed it. Any thoughts? Error is noted in code below. Any help would be appreciated, thanks.

Exception in thread "main" java.lang.NumberFormatException: For input string: "111001101100111"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
at java.lang.Integer.parseInt(Integer.java:461)
at java.lang.Integer.valueOf(Integer.java:554)
at MP1.combine(MP1.java:96)
at MP1.shiftRight(MP1.java:76)
at MP1.main(MP1.java:131)

public Integer combine(Register register, int numberOfBits) {
    String C1 = Integer.toBinaryString(register.C);
    String A1 = Integer.toBinaryString(register.A);
    String Q1 = Integer.toBinaryString(register.Q);

    C1 = String.format("%1s", C1).replace(' ', '0');
    A1 = String.format("%" + numberOfBits + "s", A1).replace(' ', '0');
    Q1 = String.format("%" + numberOfBits + "s", Q1).replace(' ', '0');

    String comboS = C1 + A1 + Q1;

    //Says error is here (below)
    Integer comboI = Integer.valueOf(comboS); 

    return comboI;
}
Was it helpful?

Solution

The max value of Integer is 2147483647, and obviously 111001101100111 is much bigger than Integer.MAX_VALUE.

Integer.valueOf(comboS) calls Integer.parseInt(str) eventually. That's why you received a NumberFormatException.

If your want to parse 111001101100111 in binary rather than decimalism. Integer.parseInt(comboS, 2) will work.

Or use BigInteger instead, which has no upper limit.

OTHER TIPS

Print out your comboS string before trying to get the valueOf it, and you will see the strange number you have.

I am guessing that it does not fit into an Integer.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top