0

How is it possible in java to have an int array and add all values from the array to a numerical series.

For example:

int[] num= new int[9];
for(int i=0; i<num.length; i++) {
num[i] = i;
}

and I need one integer variable like:

int a = 12345678910

copied from the array.

thx a lot in advance!

wundidajah
  • 177
  • 2
  • 6
  • Look into below thread : http://stackoverflow.com/questions/2674707/how-to-concatenate-int-values-in-java –  Nov 14 '13 at 19:54
  • 1
    I am not sure what you are asking. You are declaring array that can have `9` elements but in `for` loop you are trying to put to array value at index greater than max index of array. Also `12345678910` cant be integer since max integer is `2147483647`. It seems that this is [XY problem](http://meta.stackexchange.com/q/66377/186652) so maybe tell us what would be purpose of this value. Maybe you should use `String` or `BigInteger` instead `int`? – Pshemo Nov 14 '13 at 19:55
  • @Praveen : That question is about concatenating integer digits to a String. – Lion Nov 14 '13 at 19:57
  • Thank you so much guys! It works perfectly with the StringBuilder and a long variable. – wundidajah Nov 14 '13 at 20:12

3 Answers3

0

It seems most natural to use the StringBuilder class, as this handles your appending 2 digit numbers most easily:

StringBuilder sb = new StringBuilder();

for(int i = 0; i < 11; i++) {
    sb.append(i);
}

int a = Integer.parseInt(sb.toString());
quazzieclodo
  • 831
  • 4
  • 10
0
int a;
String aStr = "";
int[] num= new int[9];
for(int i=0; i<11; i++) {
aStr = aStr + num[i];
}

a = new Integer(aStr);
Alexis C.
  • 91,686
  • 21
  • 171
  • 177
csn
  • 376
  • 7
  • 18
0

There are 2 problems in your code which you'll need to fix first:

  • your array index is bigger than the size of the array (11 > 9)
  • the number you're assigning to 'a' is too big for the integer type

You could try this as a solution:

    StringBuilder numbers = new StringBuilder();

    int[] num = new int[9];
    for (int i = 0; i < num.length; i++) {
        num[i] = i;

        numbers.append(i);
    }

    long a = Long.valueOf(numbers.toString());

    System.out.println(a);

Note that you'll still need to check that the final output of 'numbers' is not too big for a long. If it is you'll need to use a data type that can accommodate the resulting value.

Sean Landsman
  • 7,033
  • 2
  • 29
  • 33