This site requires JavaScript, please enable it in your browser!
Greenfoot back
Mepp
Mepp wrote ...

2013/2/27

Split an long in the seperat numbers

Mepp Mepp

2013/2/27

#
Hi, I searching for a way to split up the individual numbers of a variable(type=long) to several integers in an Array, so if i have the long x=54321, i later have an array a with the value a=5, a=4, and so on.
Jonas234 Jonas234

2013/2/27

#
public static ArrayList<Integer> test(int x)
    {
        ArrayList<Integer> intList = new ArrayList<Integer>();
        int i =1;
        while (x!=0)
        {
            int array = x%(int) (Math.pow(10,i));
            x=x-array;
            if(i>1)
            {
                intList.add(array/(int) (Math.pow(10,i-1)));
            }
            else
            {
                intList.add(array);
            }
            i++;
        }
        return intList;
    }
If you really want an Array instead of an ArrayList you just need to determine the size of the Array beforehand. And of course you need to exchange the int with a long but it shouldn't really matter.
Mepp Mepp

2013/2/27

#
Which ints should I replace, im just getting Errors?
Jonas234 Jonas234

2013/2/27

#
public static ArrayList<Long> test(long x)
    {
        ArrayList<Long> longList = new ArrayList<Long>();
        int i =1;
        while (x!=0)
        {
            long array = x%(long) (Math.pow(10,i));
            x=x-array;
            if(i>1)
            {
                longList.add(array/(long) (Math.pow(10,i-1)));
            }
            else
            {
                longList.add(array);
            }
            i++;
        }
        return longList;
}
Nearly every long. Now it is working for long.
Mepp Mepp

2013/2/27

#
Ok, and how can I get some values out of this? My code was this:
runTime=makeRTime(rTime);
int Lenght=getLenght(rTime);
        while(Lenght!=0){
            Number n=new Number(runTime[Lenght]);
        }
It marked runTime and says "array.required, but java.util.ArrayList<java.lang.Long> found"
danpost danpost

2013/2/27

#
As an alternative, the following will do the job:
// with
long x = 54321;
// use
String xStr = "" + x;
int[] a = new int[xStr.length()];
for (int i=0; i<a.length; i++) a[i] = Integer.valueOf(xStr.substring(i, i+1));
BTW, this will work for any non-negative whole numbers (0, 1, 2, ...).
You need to login to post a reply.