0
Array
int[] list = {1,2,3,5,4}; for (int i = 0, j = list.length - 1; i < list.length; i++, j--) { int temp = list[i]; list[i] = list[j]; list[j] = temp;} I'm trying reverse the elments in array list but this doesn't work..please how do I go about it?
4 Respostas
+ 1
I think you've overcomplicated it bud. You pretty much solved it in your for loop() without all those extra variables and list switching. Just put in System.out.println(list[j]);
public class Program {
public static void main(String[] args) {
int[] list = {1,2,3,5,4};
for(int i = 0, j = list.length - 1;
i < list.length; i++, j--)
{
System.out.println(list[j]);
}
}
}
0
your code is
public class Program {
public static void main(String[] args) {
int[] list = {1,2,3,5,4};
for(int i = 0, j = list.length - 1;
i < list.length; i++, j--)
{
int temp = list[i];
list[i] = list[j];
list[j] = temp;
System.out.println(list[j]);
}
}
}
________
output :
1
2
3
2
1
0
The output should be 4 5 3 2 1
0
try this way
List<Integer> list = Arrays.asList(1, 2, 3, 5, 4);
System.out.println(list);
Collections.reverse(list);
System.out.println(list);
or this way
public class Program {
public static void reverse(int[] args) {
int arr[] = {1,2,3,5,4};
for(int i = 0; arr.length / 2; i <++)
{
int temp = arr[i];
arr[i] = arr[arr.length - i - 1];
arr[arr.length - i - 1] = temp;
System.out.println("myArray[" + i + "] =
" + arr[i]);
}
}
}