Reputation:
I am creating a method called swapElements()
. It takes an array of integers, and two integer indexes. The method should swap the values of the array elements with the specified indexes.
public class{
int swapElements(int[] number, int value1, int value2){
int temp = number[value1];
number[value1] = number[value2];
number[value2] = temp;
}
}
Upvotes: 0
Views: 83
Reputation: 1926
In such cases the return
type is not strictly required. So, you should return void
. But if you indeed want to return something, consider returning boolean
to specify if the swap happened or not. More precisely you can include the swap code into try catch
block which returns True
if the swap happened without any error and False
otherwise.
Upvotes: 0
Reputation: 4481
you can just make it return void. or maybe a boolean to indicate that the sawp happened, with no errors. like index out of range error.
Upvotes: 2
Reputation: 86774
As you have presented it, this method does not need to return anything, and should probably be declared void
. However, if there is a specific contract it needs to fulfill then you should return whatever the interface definition says it should return.
Upvotes: 3
Reputation: 59363
There are four things wrong with your code.
return number;
, because you want to return the array with swapped elements.int[]
(like int[] swapElements
), not an int
.public class IntArraySwapper { ...
.static
. Without using that keyword, you must call it on an instance, like new IntArraySwapper().swapElements(...)
. Since this method has nothing to do with class instances, simply make it static (static int[] swapElements
) so that you can call it like IntArraySwapper.swapElements(...)
.Note that the method will also modify the original array, so techinically you don't need to return anything. If you want, you could just make it a void
method and use the old array.
Upvotes: 2