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.
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.
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.
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.
You should put your code inside the main block.
public static void main(String[] args)
{
league.addplayer(ceri);
}
Related
I'm making a program in java to register players and add them in an arraylist. My method for adding players is this:
void registerNewPlayer() {
System.out.print("Name?> ");
String name = input.nextLine();
System.out.print("Game?> ");
String game = input.nextLine();
System.out.print("Age?> ");
int age = input.nextInt();
Player player = new Player(name, game, age);
players.add(player);
}
my problem is that i don't know where to put
ArrayList<Player> players = new ArrayList<>();
if i have it in main, the method doesn't know what players is, but if i have it in the class i get a "Cannot make a static reference to the non-static field players" exception, when i try to print it from main. What's the best way of solving this.
Update: thanks for the help, i realized that since my command loop is already running on an instanced version of my class there is actually no problem, there was only a problem when i tried to test my method outside the instanced command loop.
If you'd like to have it at the class level, escape the static context.
public class YourClass {
ArrayList<Player> players = new ArrayList<>();
public static void main(String[] args) {
new YourClass(); // or YourClass yourClass = new YourClass();
}
// Create an instance of YourClass to leave the static context
public YourClass() {
registerNewPlayer();
}
public void registerNewPlayer() {
System.out.print("Name?> ");
String name = input.nextLine();
System.out.print("Game?> ");
String game = input.nextLine();
System.out.print("Age?> ");
int age = input.nextInt();
System.out.print("Weight?> ");
int weight = input.nextInt();
Player player = new Player(name, game, age, weight);
players.add(player);
}
}
I thinik this is the best solution for your problem. I hope it helps :)
Your Player class:
public class Player {
private static ArrayList<Player> _players = new ArrayList<Player>();
private String name;
private String game;
private int age;
private int weight;
public Player(String name, String game, int age, int weight){
this.name = name;
this.game = game;
this.age = age;
this.weight = weight;
}
public static void AddPlayer(Player player){
_players.add(player);
}
public static ArrayList<Player> getPlayers(){
return _players;
}
}
Now you can create some players and get them as follow:
... main ...
.
.
.
Player p1 = new Player("Name1", "Game1", 20, 70);
Player p2 = new Player("Name2", "Game2", 30, 80);
Player p3 = new Player("Name2", "Game3", 25, 73);
Player.AddPlayer(p1);
Player.AddPlayer(p2);
Player.AddPlayer(p3);
ArrayList<Player> allPlayers = Player.getPlayers();
.
.
.
Let me know if it is working for you !
The error you get is because you are trying to access a non-static variable (i.e. a value or object that exists only in instances of that class) from outside of such an instance. What you can do is to create an object of that class to be able to access the players through it:
public class Demo {
private List<Player> players = new ArrayList<>();
public static void main(String[] args) {
Demo demo = new Demo();
demo.registerNewPlayer();
System.out.println(demo.players);
}
private void registerNewPlayer() {
System.out.print("Name?> ");
String name = input.nextLine();
System.out.print("Game?> ");
String game = input.nextLine();
System.out.print("Age?> ");
int age = input.nextInt();
Player player = new Player(name, game, age);
players.add(player);
}
}
By creating an object of the class and executing the method as well as access the variable through it, allows you to do what you want (if I understood correctly that is).
Further reading material:
Java: when to use static methods
Type List vs type ArrayList in Java (you may have noticed that I changed the type of players to List<Player> from ArrayList<Player>)
What is the difference between public, protected, package-private and private in Java? (you may have noticed the private keyword on the list and the method)
Globally declare the list.
ArrayList<Player> players = new ArrayList<>();
So I am programming the game War, and I need to put all of the methods in the main class. I am having trouble initializing the variables due to some errors.
public class Main {
public Player<Card> player1 = new Player<Card>();
public Player<Card> player2 = new Player<Card>();
public Player<Card>[] players = new Player[2];
players[0] = player1;
players[1] = player2;
public static void main(String[] args) {
}
}
In those lines of code, after I make the array, I get an error that says:
"Multiple markers at this line
Type safety: The expression of type Player[] needs unchecked conversion to conform to Player[]
Syntax error on token ";", { expected after this token"
The Player class is extending a stack of type Card.
Any suggestions are welcome.
Thanks.
Statements such as
players[0] = player1;
players[1] = player2;
can't be done outside of a method or constructor.
You can put them in the constructor :
public Main () {
players[0] = player1;
players[1] = player2;
}
You can use an initializer block if you want to do it outside of Main:
class Main {
public Player<Card> player1 = new Player<Card>();
public Player<Card> player2 = new Player<Card>();
public Player<Card>[] players = new Player[2];
{
players[0] = player1;
players[1] = player2;
}
public static void main(String[] args) {
}
}
Or alternatively, provide a constructor and initialize the instance variables (players/1/2) in that constructor.
I guess you can use a static block in the class if you are not going to initialize variables in constructor, you have to make variables static and try
static {
players[0] = player1;
players[1] = player2;
}
I am trying to add newly created objects to an ArrayList in the constructor of a class. The new objects are being created in another class in the main method.
Main method:
public static void main(String[] args) {
// TODO code application logic here
Player p1 = new Player("Peter");
}
My Player class:
public class Player {
protected static int age;
protected static String name;
protected static ArrayList players = new ArrayList();
Player(String aName) {
name = aName;
age = 15;
players.add(new Player()); // i know this doesn't work but trying along these lines
}
}
You have to edit the line
players.add(new Player());
to
players.add(this);
Also, there is no need to make the age and name static
I suggest you should have the following code instead
import java.util.ArrayList;
public class Player {
protected int age; //static is removed
protected String name; // static is removed
protected static ArrayList<Player> players = new ArrayList<Player>(); //this is not a best practice to have a list of player inside player.
Player(String aName) {
name = aName;
age = 15;
players.add(this); // i know this doesn't work but trying along these lines
}
public static void main(String[] args) {
// TODO code application logic here
Player p1 = new Player("Peter");
}
}
It sounds like you're actually asking how to refer to the instance you're constructing.
That's what the this keyword does.
This post is old, but for someone with similiar needs I suggest doing it like this:
Main class:
public static void main(String[] args) {
//TODO code application logic here
java.util.List<Player> players = new java.util.ArrayList<>(); //list to hold all players
Player p1 = new Player("Peter"); //test player
players.add(p1); //adding test player to the list
players.add(new Player("Peter")); //also possible in this case to add test player without creating variable for it.
}
Player class:
public class Player {
private final int age = 15; //if you always going to use 15 as a age like in your case it could be final. if not then pass it to constructor and initialize the same way as the name.
private String name;
Player(String name) { //variable name can be the same as one in class, just add this prefix to indicated you are talking about the one which is global class variable.
this.name = name;
}
}
Generally you should avoid using static keyword on variables which supposed to be different in each instance of that class. Avoid having object of itself inside.
I'm working on a personal project. It will be a card game that you might for instance compare to pokemon. unfortunately, I'm running into an error and I can't figure out what causes it. I'd appreciate any help!
okay, so I've got the card class (I've left out unnessesary attributes) with a constructor
public class Card
{
String name;
String cardID;
int strFire;
int strEarth;
public Card(String n, String id, int fire, int earth)
{
name = n;
cardID = id;
strFire = fire;
strEarth = earth;
}
}
then I've got the Deck class, which should create the instances of all cards.
public class Deck
{
static void createDeck()
{
Card hoax06 = new Card("Nirwadas the Traveler", "hoax06", 3, 2);
System.out.println(hoax06.name); // this works
}
}
and finally, I've got the Game class which holds main.
public class Game
{
public static void main(String[] args)
{
Deck.createDeck();
System.out.println(hoax06.name); // hoax06 cannot be resolved to a variable
}
}
I know the answer is probably quite simple but java's accessing system still confuses me. I've also browsed the forum for similar errors but have been unable to apply them to my case. how should I refer to a card from within main?
The card instance is created in the Deck class, so the Game class has no direct knowledge of it. Also, as soon as the createDeck() method ends you lose your reference to the card and the instance is gone.
Here's a simple example:
public class Deck
{
public Card hoax06;
static Deck createDeck()
{
Deck deck = new Deck();
deck.hoax06 = new Card("Nirwadas the Traveler", "hoax06", 3, 2);
return deck;
}
}
public class Game
{
public static void main(String[] args)
{
Deck deck = Deck.createDeck();
System.out.println(deck.hoax06.name); // this is where the error occurs
}
}
You never made hoax06. That is why the error is occurring.
Deck.createDeck();
System.out.println(hoax06.name);
Here are some options:
Make createDeck() return the card
Make a static Card in Deck, so you could use Deck.hoax06.name
try this:
public class Deck
{
static Card createDeck()
{
Card hoax06 = new Card("Nirwadas the Traveler", "hoax06", 3, 2);
System.out.println(hoax06.name); // this works
return hoax06; //return the object
}
}
public class Game
{
public static void main(String[] args)
{
Card c=Deck.createDeck(); //get the object
System.out.println(c.name); // use it here
}
}
You could create an enum (perhaps called Cards), listing all your cards, then access them from inside your Game class (or anywhere else) by using Cards.HOAX06.name
For example something like this:
enum Cards {
HOAX06("Nirwadas the Traveler", 3, 2),
HOAX07("Something else", 5, 2)
//list all your cards here in the same way
;
String name;
int strFire;
int strEarth;
Cards(String name, int fire, int earth){
this.name = name;
this.strFire = fire;
this.strEarth = earth;
}
}
Then to call it from another class:
public static void main(String[] args) {
System.out.println(Cards.HOAX06.name);
System.out.println(Cards.HOAX07.strEarth);
System.out.println(Cards.HOAX06.strFire);
}
All Enums are static and final by default you couldn't change the values once they were created, but then I'm guessing that for a deck of cards you probably won't want to..
I have an array of Person in my main method, and I have to pass in that array to PlayGame() method in the class Game. How do you do that?
public class RollOff {
public static void main(String[] args) throws IOException{
int numPeople;
int a;
System.out.println("How many people will play the game?");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s = br.readLine();
numPeople = Integer.parseInt(s);
if ((numPeople >= 2) && (numPeople <= 10)) {
Person[] p = new Person[numPeople];
for (a = 0; a < numPeople; a++) {
p[0] = new Person(a);
}
}
}
}
public class Game extends RollOff{
int numPeople;
int a;
void PlayGame() {
}
}
You need to use parameters to do that:
void playGame(Person[] p){
...
}
Now simply call
public static void main(String[] args){
...
game.playGame(p);
}
Because playGame is not a static method, you'll either need to make it static and call Game.playGame(p) or you'll need to create an instance of Game: Game game = new Game() followed by a call of game, as shown in the example above.
public void play(Person[] person) {
// code
}
// The call
play(person);
You can simply add a Person array parameter to the PlayGame
void playGame(Person[] personArray){//logic of the method}
Then all you have to do is call the playGame method from the main method by creating a new instance of the class Game
Game game = new Game();
game.PlayGame(p);
here "p" is your persons array.
The main class should create an instance of Game, and pass the array of players to the constructor:
Game game = new Game(p);
game.playGame();
The Game class should thus have the following field and constructor:
private Person[] players;
public Game(Person[] players) {
this.players = players;
}
Note that methods should start with a lower-case letter to follow Java naming conventions, and that your loop has a bug: it always sets the first element of the array instead of initializing every element.
Finally, give meaningful names to variables: players is much more readable than p.