Java error-message - 'void' type not allowed here, when calling a method that returns an integer

1.2k Views Asked by At

I've had a look throughout various forums and sites trying to find out where I'm going wrong but with no luck.

public void updatePlayerLabels()
{
    if(currPlayer == 0)
        lblP1Name.setText(lblP1Name.setText(myPlayers[currPlayer].getName() + " - " + myPlayers[currPlayer].getScore()));
    else
        lblP2Name.setText(lblP2Name.setText(myPlayers[currPlayer].getName() + " - " + myPlayers[currPlayer].getScore()));
}

the error seems to appear where I call the getScore() methods on both statements. I get 2 "'void' type not allowed here" messages. Here is a snippet of the player class.

public Player(int number, String name)
{
    this.number = number;
    this.name = name;
    score = 0;
}

public int getScore()
{
    return score;
}

As far as I can tell I should not be seeing that error as I set score to 0 in the constructor and I construct the players before that method is called.

Also I use the getScore() method elsewhere in the code without any problems, I am sure this is the problematic method as when I remove it from those 2 lines the error disappears.

3

There are 3 best solutions below

1
On BEST ANSWER

You are calling lblP1Name.setText() twice (the second time with the "result" of calling lblP1Name.setText())

It should be:

if(currPlayer == 0)
    lblP1Name.setText(myPlayers[currPlayer].getName() + " - " + myPlayers[currPlayer].getScore());
else
    lblP2Name.setText(myPlayers[currPlayer].getName() + " - " + myPlayers[currPlayer].getScore());
0
On

Your code reads

 lblP1Name.setText(lblP1Name.setText(.....));

The inner set text call will return the void that is passed to the outer call. This causes the error.

0
On

In this part:

lblP1Name.setText(lblP1Name.setText(...

The method setText() receives a String and returns void, you 're trying to set the text of lblP1Name but the inner lblP1Name.setText will return void.

Try this instead:

public void updatePlayerLabels() {
    if (currPlayer == 0)
        lblP1Name.setText(myPlayers[currPlayer].getName() + " - " + myPlayers[currPlayer].getScore());
    else
        lblP2Name.setText(myPlayers[currPlayer].getName() + " - " + myPlayers[currPlayer].getScore());
}