Results 1 to 3 of 3
  1. #1
    Ichythus is offline Member
    Join Date
    Jun 2010
    Posts
    2
    Rep Power
    0

    Default 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.

  2. #2
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,449
    Rep Power
    25

    Default

    answer = nums
    Looks like answer and nums refer to the same array. So answer[0] is the same memory location as nums[0].
    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]);

  3. #3
    Ichythus is offline Member
    Join Date
    Jun 2010
    Posts
    2
    Rep Power
    0

    Default

    Quote Originally Posted by Norm View Post
    Looks like answer and nums refer to the same array. So answer[0] is the same memory location as nums[0].
    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]);
    Yeah, okay.
    I stored nums[0] and nums[nums.length - 1] in separate variables before initiating answer as nums, that seemed to work. Thanks.

Similar Threads

  1. Arrays.sort... why sorting all arrays in class?
    By innspiron in forum New To Java
    Replies: 6
    Last Post: 03-23-2010, 01:40 AM
  2. Help needed with Java exercise - Including arrays - Reward
    By TheDarkReverend in forum New To Java
    Replies: 7
    Last Post: 10-23-2008, 02:52 AM
  3. Arrays and Histogram Help Needed
    By sebbybey in forum New To Java
    Replies: 4
    Last Post: 08-15-2008, 09:01 PM
  4. Arrays and Histogram Help Needed
    By sebbybey in forum New To Java
    Replies: 3
    Last Post: 08-15-2008, 09:00 PM
  5. Help needed with java arrays code
    By d24706 in forum New To Java
    Replies: 2
    Last Post: 03-07-2008, 01:11 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •