0

I'm stuck on a probably simple thing, but I just can't figure it out. So this is the code:

List<BigInteger> list = new ArrayList<BigInteger>();
for (int i = 1; i <= 12; i++) {
    list.add(new BigInteger("i"));
}

I get the following Exception:

Exception in thread "main" java.lang.NumberFormatException: For input string: "i"

I don't understand it, i is an integer between 1-12 and it should be convertible to a BigInteger.

Zabuzard
  • 25,064
  • 8
  • 58
  • 82
J.Hurete
  • 31
  • 3
  • Please always take a look at the [documentation](https://docs.oracle.com/javase/9/docs/api/java/math/BigInteger.html#BigInteger-java.lang.String-) of a class when experiencing such issues. The documentation clearly states that the input must represent a valid `BigInteger` and the text `"i"` (literally containing only the **character** `i`) obviously is no valid number. You need to first evaluate the variable, extract its number and convert this number to a `String` like `i + ""` or `String.valueOf(i)`. – Zabuzard Mar 11 '18 at 15:47

2 Answers2

3

The string "i" is not a valid representation of a BigInteger.

As there is no constructor taking a single int parameter in the BigInteger class, you can use String.valueOf to return the string representation of the integer i:

list.add(new BigInteger(String.valueOf(i)));
Ousmane D.
  • 54,915
  • 8
  • 91
  • 126
  • Thanks, that worked out! – J.Hurete Mar 11 '18 at 15:43
  • 1
    A bit cleaner would be to use https://docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html#valueOf(long) – Pavel Horal Mar 11 '18 at 15:44
  • I think the confusion comes from `"i"` not interpreting the value of `i` but instead representing the text `"i"` literally containing the **character** `i`, not the value after interpreting `i` as variable. Especially other languages such as PHP interpret variables inside strings, Java does not. – Zabuzard Mar 11 '18 at 15:48
  • @Zabuza I guess so, in C# one could also do `$"{i}"`, which would work. I guess this is Java functioning differently as opposed to other languages. which is completely understandable IMO. – Ousmane D. Mar 11 '18 at 15:52
1
List<BigInteger> list = new ArrayList<BigInteger>();
for (int i = 1; i <= 12; i++) {
    list.add(BigInteger.valueOf(i)); // Fix
}

This way is more efficient than the selected answer because the selected one first converts the int to a String and than parses the String back into an int which is really slow.

Ma_124
  • 45
  • 1
  • 11