I've read the Oracle documents regarding scope and controlling access yet it just isn't sticking, so I'm assuming that my issue comes from my failure to understand... Anyways Here's my code. I'm trying to access the unique Player objects created in an array, and change their unique variables like their balances, using methods from the Player class. Any solutions and ESPECIALLY explanations are welcome!
public class Player
{
private int currentBal;
private String myName;
private int rollOne;
private int rollTwo;
private int rollTotal;
private int doublesCount;
private int currentPosition;
private int currentDoubles;
private int move;
private int moveMult;
private int newBal;
private boolean rollAgain;
private boolean inJail;
public Player(String userName, int changeInMoney)
{
myName = userName;
currentBal -= changeBalance(changeInMoney);
}
public int changeBalance(int changeInMoney){newBal -= changeInMoney; return newBal;}
public int viewBalance(){return currentBal;}
Here is my PlayerArray class.
public class PlayerArray
{
Scanner scan = new Scanner(System.in);
private int numbHuman;
private Player[] arr;
private String[] userName;
private int startingMoney;
public PlayerArray()
{
Scanner scan = new Scanner(System.in);
System.out.println("There will be 4 players, how many do you wish to be human? 0><4");
numbHuman = scan.nextInt();
while (numbHuman < 1 || numbHuman > 4)
{
System.out.println("Invalid entry, try again.");
numbHuman = scan.nextInt();
}
arr = new Player[numbHuman];
userName = new String[numbHuman];
startingMoney = 1500;
for(int i = 0; i < arr.length; i++)
{
System.out.println("Player " + (i + 1) + ", Please enter your first name:");
userName[i] = scan.next();
arr[i] = new Player(userName[i],startingMoney);
}
}
public Player[] getPlayerArray()
{
int charge = 500;
arr[0].changeBalance(charge);
System.out.println(arr[0].viewBalance()); //look here as example
return arr;
}
}
this is my player class, minus some methods I can't use till later. Bellow is my main method to call it,
import java.util.Scanner;
import java.util.Random;
public class Launcher
{
private Planet myTest;
private PlanetInfo myPlanetInfo;
private static Player[] arr;
public static void main(String[] args)
{
Launcher testLauncher = new Launcher();
PlayerArray myArray = new PlayerArray();
Pay myCharge = new Pay(); // continue work on charges
myArray.getPlayerArray();
//STILL TRYING TO GET BELLOW LINE TO WORK LAST NIGHT!!!
int testBal = arr[0].viewBalance(); //ERROR HERE
System.out.println("player 1's balance: " + testBal);
}
}
Error "Java.lang.NullPointerException: null"