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
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<>();
package test.arraylist;
import java.util.Scanner;
public class TestArraylist {
static Scanner keyboard = new Scanner (System.in);
static int how_many;
public static void main(String[] args) {
menu();
}
public static void menu()
{
System.out.println("1.L2C");
System.out.println("2.M2R");
int menu = keyboard.nextInt();keyboard.nextLine();
switch (menu){
case 1:
NewClass l2c = new NewClass();
System.out.println("How many:");
how_many = keyboard.nextInt();keyboard.nextLine();
for (int i=0;i<how_many;i++){
System.out.println("Insert values:");
l2c.l2c.add(keyboard.nextLine());
System.out.println("values:"+l2c.getL2c());
}
break;
case 2:
NewClass r2p = new NewClass();
System.out.println("How many:");
how_many = keyboard.nextInt();keyboard.nextLine();
for (int i=0;i<how_many;i++){
System.out.println("Insert values:");
r2p.r2p.add(keyboard.nextLine());
System.out.println("values:"+r2p.getR2p());
}
break;
}
}
public static void seats(){
System.out.println("values:"+r2p.getR2p()); // Error
System.out.println("values:"+l2p.getR2p()); // Error
}
}
---------------------------CLASS-----------------------
package test.arraylist;
import java.util.ArrayList;
public class NewClass {
ArrayList<String> l2c = new ArrayList<>();
ArrayList<String> r2p = new ArrayList<>();
public ArrayList<String> getL2c() {
return l2c;
}
public void setL2c(ArrayList<String> l2c) {
this.l2c = l2c;
}
public ArrayList<String> getR2p() {
return r2p;
}
public void setR2p(ArrayList<String> r2p) {
this.r2p = r2p;
}
}
I'm in java for only 2 weeks
In a few words, I'm going to explain what I'm trying to do.
I am creating an ArrayList, after this user is entering
values to Arraylist.
Once everything is done, I want to access data from another method and to make some math operations, I realized that I should use some sort of return, I have tried to do this, but it does not work.
I am definitely doing something wrong.Pls help to sort this out.I spent 2 days on this.
It seems what you need is the composition of the NewClass into your Main class i.e.TestArraylist , Read composition in java composition-in-java-example
Now your code should be like this,
public class TestArraylist {
static NewClass newClass = new NewClass();
---------
--------
public static void menu(){
case 1:
ArrayList<String> l2c = newClass.getL2c(); //this way you can access the data
System.out.println("How many:");
how_many = keyboard.nextInt();keyboard.nextLine();
for (int i=0;i<how_many;i++){
System.out.println("Insert values:");
l2c.add(keyboard.nextLine()); //here you need only the instance variable to add the data into the arraylist.
System.out.println("values:"+l2c.toString()); //to print the data
}
break;
//Same way you should modify the case2 as well.
case 2:
ArrayList<String> r2p = newClass.getR2p();
System.out.println("How many:");
how_many = keyboard.nextInt();keyboard.nextLine();
for (int i=0;i<how_many;i++){
System.out.println("Insert values:");
r2p.add(keyboard.nextLine());
System.out.println("values:"+r2p.toString());
}
break;
Now that composite object will be accesible in you below method because we have declared it static.
public static void seats(){
System.out.println("values:"+newClass.getR2p()); // not throw any error
System.out.println("values:"+newClass.getR2p()); // not throw any error
}
Also your Newclass should be defined like this,
public class NewClass {
private ArrayList<String> l2c = new ArrayList<String>();
private ArrayList<String> r2p = new ArrayList<String>();
public ArrayList<String> getL2c() {
return l2c;
}
public void setL2c(ArrayList<String> l2c) {
this.l2c = l2c;
}
public ArrayList<String> getR2p() {
return r2p;
}
public void setR2p(ArrayList<String> r2p) {
this.r2p = r2p;
}
}
There are many things to be corrected but as of now to make your programm work , this should suffice.
If you call seats(), you will have an error because those variables are not declared within the proper scope. To make r2p and l2c available within that method, move the variable declarations outside of the method (below the class declaration, before main()) with the initializer private static NewClass newClass;. Feel free to assign a value as needed, or employ optionals (but considering you’ve only been doing Java for 2 weeks, stay away from optionals; just make sure you assign a value).
Edit: Use static modifier on the variables, since you’re accessing from a static context.
I'm writing some code for a text based game for my Computer Science class, but I'm having some problems with this code
(java code).
The all the code works until I put in the if/else statements, so I want to know where I should be putting the statements at.
(Error Message)
Code:
import java.util.Scanner;
import java.util.ArrayList;
class Progress {
public String udc;
public String u = "up";
public String d = "down";
public void start() {
System.out.println("Hello.");
}
public void c1() {
Scanner name=new Scanner(System.in);
System.out.println("What's your name?");
System.out.println("Hello "+name.nextLine()+".");
}
public void uod() {
Scanner ud = new Scanner(System.in);
System.out.println("Up or down?");
udc = ud.nextLine();
}
public void uodc() {
System.out.println("going "+udc+".");
}
public void end() {
System.out.println("Press any key to exit");
}
}
public class APGame {
public static void main(String[] args) {
Progress p =new Progress();
p.start();
p.c1();
p.uod();
if (u.equals(udc)) {p.uodc();}
else {p.oud();}
p.end();
}}
u and udc variables are defined inside another class, that is Progress, and should be accessed (as they are public), by p.u and p.udc.
if (p.u.equals(p.udc)) ...
udc and u are instance variables of the class Progress. So the problem with the if-else statement is that you are not referencing udc from any object of the Progress class. To fix it do:
if(p.u.equals(p.udc) {
p.uodc();
}else{
p.uod();
}
public class QuestionBank {
public static void main(String[] args) {
int k = 0;
String Bank[][] = {{"The sun is hot.","A. True","B. Flase","A"},
{"Cats can fly.","A. True","B. False","B"}};
}
}
Above is my QuestionBank class that creates a 2X4 string array. First column being the question, 2nd and 3rd being the answer choices, and 4th being the correct answer.
Below is my RealDeal class.
import javax.swing.JOptionPane;
import java.util.Scanner;
public class RealDeal {
public static void main(String[] args) {
input = JOptionPane.showInputDialog(Bank[0][0]\nBank[0][1]\nBank[0][2]);
if (input == Bank[0][3]) {
input = 10;
} else {
input = 0;
}
total = input/1;
JOptionPane.showMessageDialog(null,"You scored a " + total + " out of 10. Great job!");
System.exit(0);
}
}
What I'm trying to do is to get Bank[0][0], Bank[0][1], and Bank[0][2] to output on my RealDeal class and then to check whether Bank[0][3] matches with the users input. Can anyone please help me with this. Im really new to java so if anyone could actually draw out the answer and explain it to me that would be great.
I think the best way is reading a good Java book and become familiar with the language itself and then try to solve this by your own. If you then have a real question there is no problem asking it here again. But your code is... not really working at all.
I don't think this portal is a "please do my work for me" portal.
To call anything from another class you will need to either setup a method for a return or make the variables public.
So:
public class Class1
{
// for method 1
public String s1 = "This is a string"
// for method 2
public Class1 {}
public returnString()
{
return s1;
}
}
public class CLASS2
{
public static void main(String args[])
{
// get the class
cls1 = new Class1();
// retrieving - method 1
String str = cls1.s1;
// retrieving - method2
str = cls1.returnString();
}
}
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.