问题
Why am I getting an "invalid method declaration; return type required" error on check(values); ?
public class Swap
{
int[] values = {5, 6, 7, 8, 9};
check(values);
public void swapAdjacentElemnts(int[] values)
{
for(int i=0; i<values.length - 1; i+=2)
{
int tempInt = values[i];
values[i] = values[i+1];
values[i+1]=tempInt;
}
}
public int[] check(int[] values)
{
swapAdjacentElements(values);
return values;
}
}
回答1:
You are attempting to execute code outside of a method. Your call to check
has to live inside of some kind of method, rather than in the class declaration.
If you meant for this to be in the constructor, you can do that:
public Swap()
{
check(values);
}
回答2:
You can't put method calls on the class body directly.
That call should be inside another method (just like you do with swapAdjacentElements
).
Maybe what you meant was to do the check inside the constructor of the class, or in a main method.
public class Swap
{
int[] values = {5, 6, 7, 8, 9};
public Swap() { //class constructor
check(values);
}
public static void main(String[] args) { //main method
check(values);
}
//everything else..
}
Hope that helps.
回答3:
In some cases, You should execute a function, after other methods/functions are declared.
来源:https://stackoverflow.com/questions/16045753/invalid-method-declaration-issue