Ethan
Ethan

Reputation: 25

How would I put an integer that is storing numbers into an array?

So I have an integer z that is holding the values of zip codes and i need to store each digit of the zip code in a separate part of the array. How would i be able to do this?

 private int [] zipDigits = new int [5];
 private int digitCheck;
 private int zipCode;
 public ZipCode(int z)
 {
for(int i = 0; i < 5; i++)
    zipDigits[i] = 
this.zipCode = z;

Upvotes: 0

Views: 76

Answers (4)

Daan van der Kallen
Daan van der Kallen

Reputation: 543

Something like this should work:

public int[] intToDigits(int z) {
    int n = String.valueOf(z).length();
    int[] res = new int[n];
    int i = n - 1;
    while (i >= 0) {
        res[i--] = z % 10;
        z = z / 10;
    }
    return res;
}

This first gets the length in a quite obvious matter, you could also do this using logarithms but I don't know if their precision would lead to issues. Then starts at the back of the array, takes the last digit with mod and then deletes this digit by dividing the number by 10.

EDIT: I now see that you've edited your post to state that the length is known to be 5 digits, then we don't need to calculate the length ourselves and we can use the following algorithm:

public int[] intToDigits(int z) {
    int[] res = new int[5];
    int i = 4;
    while (i >= 0) {
        res[i--] = z % 10;
        z = z / 10;
    }
    return res;
}

Upvotes: 2

MNM
MNM

Reputation: 2743

So you are asking this;

you have a

 int zip = 90210

and you want to put this into a array like this

  int [] zipArrary = new int [5];
  String changeZip = Integer.toString(zip);
 for (int i = 0; i < changeZip.length(); i++){
    char c = s.charAt(i);
    int place = Character.getNumericValue(c);
    zipArray[i] = place;      

  }

Something like this?

Upvotes: 1

granmirupa
granmirupa

Reputation: 2790

Since you know the number of digits, you can make a loop getting the rest of division for 10 and saving it into the array and then dividing for 10.

int zipCode = 1000;
int [] myArray = new int[5];
for(int i = 0; i < 5; i++){
    if(zipCode > 0){
        myArray[i] = zipCode%10;
        zipCode /= 10;
    }
    else
        myArray[i] = 0;
}

Upvotes: 1

gmiley
gmiley

Reputation: 6604

int zip = 12345;
String strZip = Integer.toString(zip);
char[] charArrayZip = strZip.toCharArray();

Now your zip is in an array of char.

Upvotes: 0

Related Questions