Results 1 to 2 of 2
  1. #1
    Yfke is offline Member
    Join Date
    Nov 2009
    Posts
    1
    Rep Power
    0

    Default int to array conversion

    Hi, I'm very very new to Java (just started learning about 3 days ago) and I have a problem.

    My goal is to convert an int (also negative numbers need to be converted!) into an array. If the int is, for example, -38921, I would want it to be stored in an array like this: {3, 8, 9, 2, 1}.

    I have come up with a solution, but somehow I feel that there must be a shorter way... I have already searched around these forums a bit, but haven't found anything. So anyway, here's (part of) my code:

    Java Code:
    int x = 87346;		// could be any number
    int length = 1; 
    
    // This loop determines how many numbers the int exists of:
    for (int i = 10; (x>=i) | (x<=-i); i *= 10) {
    	length ++;
    }
    
    // this creates a new array called "rij":		
    int[] rij;
    rij = new int[length];
    
    // this loop looks at the last number of x, stores it in the last empty space in
    // "rij" and removes the last number. Then repeats the process.
    // (e.g. 356: it stores 6 in { _, _, 6} and converts 356 to 35.)
    for(int i = 1; i <= length; i++) {
    	int g;	
    	for (g = 0; !(x%10 == 0); g++) {
    		if(x > 0) x--;
    		if(x < 0) x++;
    	}
    	rij[rij.length - i] = g;
    	x /= 10;
    }
    Is there a shorter/better way, or am I just being too optimistic :rolleyes: ? :D

  2. #2
    Arnold is offline Member
    Join Date
    Oct 2009
    Location
    Rotterdam
    Posts
    52
    Rep Power
    0

    Default

    Convert your int to a string and check it's length. With the charAt(x) method you can even check which number is on which position.
    Good luck with Java!

Similar Threads

  1. XLS to PDF conversion
    By nitin2k2k in forum Advanced Java
    Replies: 18
    Last Post: 07-02-2013, 11:17 AM
  2. Doc to Pdf conversion
    By praveen.kb in forum Advanced Java
    Replies: 2
    Last Post: 01-16-2009, 12:27 PM
  3. String Conversion....
    By hotice1027 in forum New To Java
    Replies: 8
    Last Post: 11-28-2008, 10:52 PM
  4. Conversion from wav to vox
    By bozovilla in forum Advanced Java
    Replies: 1
    Last Post: 07-31-2008, 05:54 AM
  5. Arraylist to a 2- dimension array conversion
    By mars123 in forum New To Java
    Replies: 1
    Last Post: 12-06-2007, 11:24 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •