Results 1 to 6 of 6
- 10-29-2013, 04:04 AM #1
Member
- Join Date
- Oct 2013
- Posts
- 6
- Rep Power
- 0
How to swap the first and last array value
This is what I have so far, but I am not sure how to fix it... please help... Thanks
public class SwapFandL {
public static void swap(int [] x){
int temp = x[0];
x[0] = x[x.length-1];
x[x.length-1] = temp;
}
public static void main(String[] args){
int [] x = {1, 3, 5, 7, 2, 9};
System.out.print(swap(x));
}
}
- 10-29-2013, 04:05 AM #2
Member
- Join Date
- Oct 2013
- Posts
- 6
- Rep Power
- 0
Re: How to swap the first and last array value
The output should be : 9 3 5 7 2 1
- 10-29-2013, 04:08 AM #3
Re: How to swap the first and last array value
If you get an error then you should copy and paste the full error message and indicate on which line it occurs.
Your swap method has a void return type, therefore there is nothing for the print statement to display. Also, you cannot print an array that way. You need to iterate over the array and print out each element individually.
- 10-29-2013, 04:12 AM #4
Member
- Join Date
- Oct 2013
- Posts
- 6
- Rep Power
- 0
Re: How to swap the first and last array value
This is how I changed it...
and the output I got was : [I@3dd4ab05
public class SwapFandL {
public static int[] swap(int [] x){
int temp = x[0];
x[0] = x[x.length-1];
x[x.length-1] = temp;
return x;
}
public static void main(String[] args){
int [] x = {1, 3, 5, 7, 2, 9};
System.out.print(swap(x));
}
}
- 10-29-2013, 04:14 AM #5
Re: How to swap the first and last array value
Read my entire post above!
- 10-29-2013, 04:20 PM #6
Senior Member
- Join Date
- Jan 2013
- Location
- Northern Virginia, United States
- Posts
- 6,226
- Rep Power
- 15
Re: How to swap the first and last array value
Since you are swapping elements of an array (which is a reference) you do not need to return anything. However, to print out the array you need to do what Junky recommended. Another alternative is to the Arrays class. You should find a method in that class that could be of use.
Regards,
JimThe JavaTM Tutorials | SSCCE | Java Naming Conventions
Poor planning on your part does not constitute an emergency on my part
Similar Threads
-
How do you swap the numbers and the location of their values in an array?
By xion0374 in forum New To JavaReplies: 2Last Post: 03-20-2012, 01:01 AM -
Swap 2 dimensional Array
By whit3ang3l in forum New To JavaReplies: 4Last Post: 03-06-2012, 01:53 PM -
Swap array value
By irnie1994 in forum New To JavaReplies: 1Last Post: 11-10-2011, 06:06 PM -
how can i loop my array swap
By belfast09 in forum New To JavaReplies: 3Last Post: 06-15-2011, 05:35 AM -
Multidimensional array - swap
By BeginnerNoob in forum New To JavaReplies: 13Last Post: 03-30-2011, 04:02 PM
Bookmarks