简体   繁体   中英

What should I use as the return statement?

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;
    }
}

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.

There are four things wrong with your code.

  1. The thing you're asking about: use return number; , because you want to return the array with swapped elements.
  2. Make the method return an int[] (like int[] swapElements ), not an int .
  3. Your class has no name. You need to add a name, like public class IntArraySwapper { ... .
  4. Your method should be 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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM