简体   繁体   中英

Java complains about invalid method declaration, return type required

it's for a JOptionPane YES_NO_CANCEL_OPTION I did the following method:

public NewCard()
    {
        int ans = JOptionPane.showConfirmDialog(null, "Do you wish another card?", "7 in 1", JOptionPane.YES_NO_CANCEL_OPTION );
        if (ans == JOptionPane.YES_OPTION)
        {
            ans = 1;
        }

        if (ans == JOptionPane.NO_OPTION)
        {
            ans = 2;
        }

        if (resp == JOptionPane.CANCEL_OPTION)
        {
            ans = 3;
        }
        return ans;
    }

I want to read this answer from the main but a grammatical error appears. It says: Invalid method declaration; return type required Invalid method declaration; return type required but I tried to write a return in all if statements and got the same error.

You must have the return type in the function declaration.

Your function returns an int , so:

public int NewCard() {

See the int there.

If you don't want to return anything, use void .

This really should be a comment, but I needed the formatting.

You need to be careful when you reuse a variable like ans.

The values of the following constants are:

JOptionPane.YES_OPTION = 0;
JOptionPane.NO_OPTION = 1;
JOptionPane.CANCEL_OPTION = 2;

You could have just as easily added 1 to ans as coded the 3 if statements.

The way you wrote your code:

    if (ans == JOptionPane.YES_OPTION)
    {
        ans = 1;
    }

    if (ans == JOptionPane.NO_OPTION)
    {
        ans = 2;
    }

    if (resp == JOptionPane.CANCEL_OPTION)
    {
        ans = 3;
    }

If ans = 0 (the YES option), you set it to 1 in the first if.

Then ans (your ans, not the original ans) = 1 (the NO option).

The same thing happens in the 3rd if.

So, if your user clicks on the YES button, you return a 3. If your user clicks on the NO button, you return a 3. Same for the CANCEL button. You return a 3.

Either use two different variables, change your second and third if to an else if, or just add 1 to ans.

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