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;
}
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<>();
I am making a game that requires an update class to access a game class and a main class to access both of those. The problem I am having is that I need the update class to have an updated object of the game class but I get an error whenever I try and access the game class from the Update class [error occurs on newGame.test();]
ERROR: Exception in thread "main" java.lang.NullPointerException
at Updates.updateStats(Updates.java:17)
at Game.gameLoop(Game.java:24)
at Main.main(Main.java:14)
import java.util.Scanner;
public class Main
{
static Scanner input = new Scanner(System.in);
public static void main(String[] args)
{
Game newGame = new Game();
//Updates getUpdates = new Updates();
newGame.setupGame();
Game.isRunning=true;
newGame.gameLoop();
}
}
import java.util.Scanner;
public class Game {
static Scanner input = new Scanner(System.in);
Updates getUpdates = new Updates();
public Game(){
}
String goverment;
int happyness;
double money;
int population = 1000000;
public static boolean isRunning;
private int turn = 0;
public void gameLoop(){
while (isRunning){
getUpdates.updateStats();
System.out.println("Turn: "+turn);
input.nextLine();
turn++;
}
}
public void setupGame()
{
System.out.println("Goverment: 1=Democracy 2=monarchy 3=dictatorship");
goverment = input.nextLine();
while (!goverment.equals("1")||!goverment.equals("2")||!goverment.equals("3")){
if (goverment.equals("1")){
happyness = 75;
money = 250000.0;
break;
}
else if (goverment.equals("2")){
happyness = 50;
money = 500000.0;
break;
}
else if (goverment.equals("3")){
happyness = 25;
money = 750000.0;
break;
}
else{
System.out.println("ENTER A VALID VALUE");
goverment = input.nextLine();
}
}
System.out.println("1");
}
public int getHappyness(){
return happyness;
}
public void test(){
System.out.println("MY NAME IS BOB");
}
}
import java.util.Scanner;
public class Updates {
static Scanner input = new Scanner(System.in);
public Updates(){
}
public Updates(Game newGame){
this.newGame = newGame;
}
Game newGame;
public void updateStats(){
newGame.test();
}
}
I'm sorry if this isn't very much help, but it's my first time answering a question on here.
I put your code into a test project to see where the issue was, and it seems you have a few errors.
I'll start with the Main class as it has the smallest issues.
You don't need to declare the scanner object here as it's never used. You're just allocating memory to an empty object.
Now, onto the Updates class.
Again, no need to declare a scanner here.
To use the object "newGame" you need to make sure you're making use of the Constructor:
public Updates(Game newGame){
this.newGame = newGame;
}
And not:
public Updates(){
}
Because the latter one won't set the Game object for you, and any time you access it you will get a nullpointer.
Finally, the Game class:
I'd make both the Scanner and the Updates objects private, as they're never used outside the class. If they are, make use of getters and setters.
In your Game constructor, you can actually create both the getUpdates and input objects, like so:
public Game() {
this.input = new Scanner(System.in);
this.getUpdates = new Updates(this);
}
That way whenever your game is initialized, you'll have them at the ready. As you can see, I put
new Updates(this)
which uses the Updates constructor I mentioned before. This should ultimately solve your issue.
For reference, here are the files I used/edited and it worked on my end:
Pastebin link
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);
}
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 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.