mardi 30 octobre 2018

How to Reverse an array in a method? (java) [duplicate]

This question already has an answer here:

So I have a question that tells me I need to create an int array, initialize this array with random ints between 200 and 300, and then I need to call a function which I pass this array to, and then the function should create a new array and copy the array that it's passed, but in reverse order, and then main should display the original array and the returned one. Here's what i have:

import java.util.Random;
public class Q {


public static void main(String[] args) { 
Random r = new Random();
int[] a = new int[100];
for (int i = 0; i < a.length; i++)
{
 a[i] = r.nextInt(300)+200; 
}


System.out.println(a);
System.out.println(reverse(a));

}

public static int[] reverse(int[] x)
{

int []t = new int[x.length];

for (int i = t.length-1; i >= 0; i--)
{
  t[(x.length - i - 1)] = x[i];
}
return t;
}
}

I feel like I'm on the right track, but the console ends up displaying all these weird characters. Thanks for any help.




Aucun commentaire:

Enregistrer un commentaire