Results 1 to 3 of 3
- 06-28-2010, 06:23 AM #1
Member
- Join Date
- Jun 2010
- Posts
- 2
- Rep Power
- 0
Just Began: Help needed with Arrays
I am just learning java, and would appreciate help for the problem below:
Given an array of ints, swap the first and last elements in the array. Return the modified array. The array length will be at least 1.
Here is my solution, which does not work:
public int[] swapEnds(int[] nums) {
int[] answer;
answer = new int[nums.length];
answer = nums;
answer[answer.length - 1] = nums[0];
answer[0] = nums[nums.length - 1];
return answer;
}
I cannot make the end of nums display as the beginning of int[] answer, it seems to be like a recessive gene, not showing up if answer[answer.length - 1] = nums[0]; is there.
- 06-28-2010, 01:00 PM #2
Looks like answer and nums refer to the same array. So answer[0] is the same memory location as nums[0].answer = nums
Perhaps you should use a temp variable to save the value being moved to keep it from being overwritten.
Also add some println() statements to show the values you are working with. For example:
System.out.println("nums[0]=" + nums[0] + ", answer[0]=" + answer[0]);
- 06-28-2010, 05:17 PM #3
Member
- Join Date
- Jun 2010
- Posts
- 2
- Rep Power
- 0
Similar Threads
-
Arrays.sort... why sorting all arrays in class?
By innspiron in forum New To JavaReplies: 6Last Post: 03-23-2010, 01:40 AM -
Help needed with Java exercise - Including arrays - Reward
By TheDarkReverend in forum New To JavaReplies: 7Last Post: 10-23-2008, 02:52 AM -
Arrays and Histogram Help Needed
By sebbybey in forum New To JavaReplies: 4Last Post: 08-15-2008, 09:01 PM -
Arrays and Histogram Help Needed
By sebbybey in forum New To JavaReplies: 3Last Post: 08-15-2008, 09:00 PM -
Help needed with java arrays code
By d24706 in forum New To JavaReplies: 2Last Post: 03-07-2008, 01:11 AM


LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks