Invalid method declaration issue

本秂侑毒 提交于 2019-12-24 03:29:23

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!