Ceri Westcott
Ceri Westcott

Reputation: 300

Cannot call a method?

I have a Game class and a TestGame class, I'm trying to call a method from Game to TestGame.

TestGame.java

public class TestGame {

    Players ceri = new Players("Ceri", 1);
    Players harry = new Players("Harry", 1);
    Players lewis = new Players("Lewis", 1);
    Players kwok = new Players("Kwok", 1);
    Players james = new Players("James", 1);
    Players matthew = new Players("Matthew", 1);


    Game league = new Game("League Table");

    league.addplayer(ceri);

    public static void main(String[] args) {

    }
}

and Game.java

public class Game {

    private String name;

    public Game(String name){
        this.name = name;
    }

    public void addPlayer(Players obj){

    }
}

I get red lines underneath league.addPlayer for some reason.

Upvotes: 0

Views: 111

Answers (4)

Tim B
Tim B

Reputation: 41188

league.addplayer(ceri); is code, not initializer.

You need to put it inside a method or inside an initalizer block.

In this case put it inside your main method.

Upvotes: 5

Henrique Ordine
Henrique Ordine

Reputation: 3337

You'd have to move all of these lines to the main() method:

Players ceri = new Players("Ceri", 1);
Game league = new Game("League Table");
league.addplayer(ceri);

If you move only the last one, the league and ceri variables won't be accessible, as the main method is a static method and these variables would be instance variables.

Upvotes: 2

rodridevops
rodridevops

Reputation: 1987

You should put your code inside the main block.

public static void main(String[] args) 
{
    league.addplayer(ceri);
}

Upvotes: 0

Azar
Azar

Reputation: 1106

All of your Players (and Game) are declared inside the class body. This makes them global variables with default level access. Something to note in addition to Tim B's answer.

Upvotes: 0

Related Questions