Search code examples
javacompiler-errorsvoidjcreator

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


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.


Solution

  • 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());