Question

Maybe this question is silly, but I'm new in Java and I cant figure this out...

So I have two clases - Digit and BigDigit and the problem is here Digit2.sub(Digit1); when Digit1 is negative I get

Exception in thread "main" java.lang.NumberFormatException: Illegal embedded sign character at java.math.BigInteger.(Unknown Source)

but when I tried pass as argument not Digit1, but example "-18370", then everything is ok, but basically it should be the same. If it's positive, everyting works like a charm. Can anyone give me a tip where I went wrong? Method 'add' works all the time, but 'sub' only with positive Digit1.

UPDATED This code works when Digit1 is positive or if uncomented Digit1.add( Digit2);, then works when sum is positive. But not negative :(

import java.math.BigInteger;

public class Digit {

public static void main(String[] args)
{
    BigDigit Digit1 = new BigDigit("-18730");
    BigDigit Digit2 = new BigDigit("77730");

   // Digit1.add( Digit2);
    Digit1.display();
    Digit1.reverse();
    Digit1.display();

   Digit2.sub( Digit1);
   Digit2.display();
   Digit2.reverse();
   Digit2.display();
    }
}
class BigDigit {
public String number;
public BigInteger first;
public BigInteger second;

public BigDigit(String str) {number = str;}

public String add(BigDigit sk) {
    first = new BigInteger(number);
    second = new BigInteger(sk.number);
    return number = first.add(second).toString();
}

public String reverse() {
    return number = new StringBuffer(number).reverse().toString();
}

public void sub(BigDigit sk) {
    first = new BigInteger(number);
    second = new BigInteger(sk.number);     
    }
public void display() {System.out.println(number);}
}
Was it helpful?

Solution

The problem is that you are trying to construct a BigInteger with an invalid number (03781-). This string is created by reversing -18730 in your reverse method.

This is what is printed without the addition:

C:\>java Digit
-18730
03781-
Exception in thread "main" java.lang.NumberFormatException: Illegal embedded sign character
        at java.math.BigInteger.<init>(Unknown Source)
        at java.math.BigInteger.<init>(Unknown Source)
        at BigDigit.sub(Digit.java:42)
        at Digit.main(Digit.java:15)

This is what's printed when I enable the addition

C:\>java Digit
59000
00095
77730
03777

Reversing a positive integer (59000) won't leave the embedded minus sign (00095), which is the source of the exception you are seeing.

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