Jump to content

Help with reversing my array method , and filling Array please

- - - - -

  • Please log in to reply
1 reply to this topic

#1
yeeesh

yeeesh

    Newbie

  • Members
  • Pip
  • 4 posts
Hello im brand new to this forum. I'am just starting programming and I have seeked this forum for some help with my array and array methods. My question is I need to know how to go about writing my reverse array method , and fill Array method.

So for example my array print method returns {15,24,32,40,6} i need my reverse array method to print {6,40,32,24,15}

SO far I have this when I run my the program it prints {6,40,32,1,0} I cant figure out why its not printing 24 and 15 the last 2 numbers in my array.

public static void reverseArray(int [] data)

{
for(int i = 0; i < data.length / 2; i++)
{

data[i] = data[data.length - i - 1];
data[data.length - i - 1] = i;


}
}
}



as for my fill array method will create an array , and then fill them with random integers between 0 and 42 in my case but I cant use math.random it has to be a method using

Random rng = new Random();
int num = rng.nextInt();

here is what I have so far any help would be greatly appricated

thank you

Edited by yeeesh, 21 September 2011 - 12:19 PM.


#2
lethalwire

lethalwire

    while(false){ ... }

  • Members
  • PipPipPipPipPipPipPip
  • 748 posts
  • Programming Language:Java, PHP
  • Learning:Java, PHP
data[data.length - i - 1] = i;
you're setting a value in your array to a position. I think you were meaning data[data.length-i-1] = data[data[i]

But still in this case you're losing values. You need a temporary holding variable.

Example:

data[0] = 0

data[1] = 1

data[2] = 2


Let's say we want to swap position 0 and 2.
This is what you have:

data[0] = data[2] 

//so data[0] = 2 now

data[2] = data[0]

//But remember data[0] now contains the number 2!

//so you're saying

data[2] = 2


// here's what your array looks like now

data[0] = 2

data[1] = 1

data[2] = 2


//solve this by adding a temporary holding variable

int temporaryVariable = data[0];

data[0] = data[2];

data[2] = temporaryVariable;






1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users