Larisa
Larisa

Reputation: 791

Convert character to BigInteger

I know there is quite all of posts for converting characters to integers, strings to BigInteger-s, int-s to BigInteger-s, ... but I just can't figure out why this does not work.

Scanner sc = new Scanner(System.in);

BigInteger sum = 0;
String line = "";
while (sc.hasNext()) {
line = sc.next();
for (char character: vrstica.toCharArray()) {
    sum = sum.add(BigInteger.valueOf(Character.getNumericValue(character)));
    }
}

I do have Scanner and BigInteger imported. The input data is constructed of lines with numbers, like this: 7218904932283439201\n7218904932283439201 ...

If I understand correctly, addition for BigInteger-s should be written like this: bigInteger1.add(bigInteger2), where both numbers are of type BigInteger. So I should convert that character of type char to type int and then convert that int value to BigInteger with method BigInteger.valueOf(), which takes an int argument.

The error I am getting is the following: incompatible types: int cannot be converted to BigInteger

I am not seeing where I could be wrong so I would appreciate if anyone could point out my mistake.

Upvotes: 1

Views: 3153

Answers (1)

Yassin Hajaj
Yassin Hajaj

Reputation: 21975

You're trying to assign an int literal to a BigInteger object.

BigInteger sum = 0;

Use instead the following

BigInteger sum = BigInteger.ZERO;

Upvotes: 5

Related Questions