1

I believe the code works but the tester code isn't and I'm not sure why. I'm trying to swap the first and last value in an array.

public class ArrayMethods {

 private int[] values;
 public ArrayMethods(int[] initialValues) {
    values = initialValues;
  }
 public void swapFirstAndLast() {
    int lastvalplace = values.length;
    int firstval = values[0];
    values[0] = values[lastvalplace];
    values[lastvalplace] = firstval;
 }

 public static void main(String[] args) {
     ArrayMethods initialValues = new ArrayMethods(int[] 50, 32, 4, 9, 2);
     swapFirstAndLast = new swapFirstAndLast(values);
 }

}
3
  • "I believe the code works" You should test it and be sure, not just assume. Also, what does happen with the "test code"? Commented Nov 12, 2016 at 21:01
  • 1
    what do you mean by "doesn't work"? I guess it doesn't even compile, does it? Commented Nov 12, 2016 at 21:02
  • the last element in an array is array[array.length - 1] (not array[array.length] like in your code) Commented Nov 12, 2016 at 21:02

1 Answer 1

2

Well, it's basic swap + 0-indexed array case.

int lastElement = values[values.length-1];
values[values.length-1] = values[0];
values[0] = lastElement;

Your code generates ArrayOutOfBoundsException which gives a stacktrace which prints you the line in which the problem is and the information that the index is too large. It also gives you the index.

You got something like that:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 26
at ArrayMethods.swapFirstAndLast(ArrayMethods.java:10)

Remember, the last element of an array in Java is array[array.length-1]

And there is also one problem. Your main:

ArrayMethods initialValues = new ArrayMethods(new int[]{50, 32, 4, 9, 2});
initialValues.swapFirstAndLast();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.