KillerHawx
KillerHawx

Reputation: 41

Adding integer elements to list JAVA

I am trying to separate digits from an Integer and then put them into an array.

All elements, except for the first, are printing as 0. Could someone explain why this is it happening?

public class Doom{
    public static void main(String[] args){
        int number = 1234;
        int[] list = new int[5];
        while (number > 0) {

            int x = 0;
            int fork = (number%10);
            System.out.println(fork);
            list[x] = fork;
            x++;
            number = number / 10;
        }
        for (int x : list){
            System.out.println(x);
        }

    }
}

Upvotes: 1

Views: 299

Answers (4)

VHS
VHS

Reputation: 10184

There are quite a few errors in your program. Biggest one is that you are inializing x to 0 and then incrementing it by 1 within the while loop. It will keep storing your digits at the same location (0th place). Compare the following snippet and try to learn your mistakes:

public class Doom{
    public static void main(String[] args){
        int number = 1234;
        int[] list = new int[String.valueOf(number).length()];
        int x = 0;
        while (number > 0) {        
            int fork = (number%10);
            System.out.println(fork);
            list[x] = fork;
            x++;
            number = number / 10;
        }
        for (int y : list){
            System.out.println(y);
        }

    }
}

Upvotes: 0

Miki P
Miki P

Reputation: 652

You are reinitializing x to 0 every time. Declare it outside of the while loop.

Upvotes: 0

Makoto
Makoto

Reputation: 106430

You keep redeclaring x in your loop, causing only the first index to have meaningful data. Move it to the outside of your loop.

Upvotes: 1

Jonathan Gilbert
Jonathan Gilbert

Reputation: 3840

The problem is that you are declaring x inside the loop, so it gets reset to 0 each time. You want to move the int x = 0; line to be above the while (number > 0) { line, outside of the loop. Then it will be initialized to 0 only once, and each pass through the loop can assign it a new value with the x++ line.

Upvotes: 2

Related Questions