Changing data in an Object Array - java

I have been trying to make a game for a friend, but I'm having a problem with getting my line player[i].setName(getName(pn)); in class Players to work. I want to be able to set the names of the players, or change them, in the list. but I keep getting errors at this line. This happened after i changed the public variables in class Player from static.
"Exception in thread "main" java.lang.NullPointerException
at worldhomicide.drinkinggame.PlayerInfo.Players.setPlayers(Players.java:16)
at worldhomicide.drinkinggame.main.Game.main(Game.java:25)"
Any help would be greatly appreciated! I posted all needed code below.
Game Class
public class Game{
public static void main(String[] args) {
MessageHandler.gameRules(); // Display Game Information
Players.getAmount();Players.setPlayers(); // Get player data
System.out.println("What player would you like to look up?");
int choice = Integer.parseInt(EventHandler.keyboard.next()); choice -= 1;
System.out.println(Players.player[choice].name);
}
}
Players Class
public class Players extends EventHandler {
public static int playerAmount;
public static Player[] player;
public static void setPlayers(){
player = new Player[playerAmount];
for(int i = 0; i < player.length; i++){
int pn = i+1;
player[i].setName(getName(pn));
}
}
public static void getAmount(){
MessageHandler.playerAmount();
playerAmount = Integer.parseInt(keyboard.next());
}
}
Class EventHandler
public class EventHandler {
public static Scanner keyboard = new Scanner(System.in);
public static String getName(int playerNumber){
System.out.println("What is player " + playerNumber + "'s name?");
String name = keyboard.next();
return name;
}
}
Player Class
public class Player {
public String name;
public int score;
public void setName(String name){
this.name = name;
}
}

Note that in your setPlayers() method, inside the loop, you didn't create Player object before accessing the player[i].setName() method.
for(int i = 0; i < player.length; i++){
int pn = i+1;
player[i] = new Player(); //you need to create Player object
player[i].setName(getName(pn));
}

Related

Trying to solve a Simple RPG game

I'm trying to solve a task that's a bit too much for me. The idea is to have a simple RPG game with the parent class (AllPlayers) and a subclass PlayerOne. I'm struggling with the calling of the player profession and his inventory system. I need to print how many coins the player has in its pocket, too.
MAIN:
import java.util.Scanner;
public class Main {
public static Scanner scanner = new Scanner(System.in);
public static String username;
public static PlayerOne player;
public static void main(String[] args) {
System.out.println("Choose your name: ");
username = scanner.nextLine();
System.out.println("Choose your profession: \n" +
"Press 1 for a knight class\n" +
"Press 1 for a rider class\n" +
"Press 1 for a mage class");
player = new PlayerOne(username);
player.displayPlayerOne();
player.displayPlayerInventory();
player.displayPocketCoins();
player.displayPlayerProfession();
}
}
As you can see, I set the getters and setters but that's the farthest I have gone so far. Can you provide me with some clues on how to
call the profession in the main?
call the inventory in the main?
I guess I'll figure out how to call coins in the main later, it will be quite the same as with profession and inventory.
Thank you!
AllPlayers (SUPERCLASS)
public class AllPlayers {
protected String name;
private int level;
private int health;
private int damage;
public AllPlayers(String name, int level, int health, int damage) {
this.name = name;
this.level = level;
this.health = health;
this.damage = damage;
}
}
And here is the player class:
public class PlayerOne extends AllPlayers{
private String [] inventory;
private int coins;
private String [] professions;
public PlayerOne(String name) {
super(name, 1, 20,5);
this.professions = getProfessions();
}
public void setProfessions(String[] professions) {
this.professions = professions;
}
public String[] getProfessions() {
return this.professions;
}
public void setCoins() {
this.coins = coins;
}
public int getCoins() {
return coins;
}
public void setInventory() {
this.inventory = inventory;
}
public String[] getInventory() {
return inventory;
}
public void displayPlayerOne() {
System.out.println("Your name is " + super.name);
}
public void displayPlayerInventory() {
inventory[0] = "knife";
inventory[1] = "sword";
inventory[2] = "spear";
inventory[3] = "potion";
}
public void displayPocketCoins() {
coins = 50;
}
public void displayPlayerProfession() {
professions[0] = "knight";
professions[1] = "rider";
professions[2] = "mage";
}
}
call the profession in the main?
Well, you already have the type declaration PlayerOne player; so just call player.getProfessions() and use the array.
call the inventory in the main?
Just the same: player.getInventory().
However, note that your design is somewhat flawed (although since you're a beginner don't bother too much). The class name PlayerOne indicates any other player (e.g. PlayerTwo) would be different, but that's probably not the case. Also, AllPlayers doesn't actually indicate a class, but it looks more like a collection.
You might think about changing your class names, e.g. assuming AllPlayers will be used for NPCs as well, you could name it Character while the class for players is called Player. Doing this you could have multiple players if needed: Player playerOne, Player playerTwo etc.

Setters And Getters to different Class

My problem is that, simply I don't know what code to use to get my value from my getX method to my other classses main method.
package hangman;
public class Hangman {
private int triesLimit;
private String word;
public void setTriesLimit(int triesLimit) {
this.triesLimit = triesLimit;
}
public void setWord(String word) {
this.word = word;
}
public int getTriesLimit() {
return this.triesLimit;
}
public String getWord() {
return this.word;
}
#Override
public String toString() {
return ("Enter Secret Word " + this.getWord()
+ ".\nEnter max # of tries (Must be under 7) "
+ this.getTriesLimit());
}
}
Thats from the sub-class and I am trying to store the value of the triesLimit into the main of this classes main method
package hangman;
public class PlayHangman {
public static void main(String[] args) {
Hangman hangman = new Hangman();
Scanner scn = new Scanner(System.in);
int triesCount = 0;
int correctCount = 0;
hangman.toString();
int triesLimit = hangman.getTriesLimit();
String secretWord = hangman.getWord();
StringBuilder b = new StringBuilder(secretWord.length());
for (int i = 0; i < secretWord.length(); i++) {
b.append("*");
}
char[] secrectStrCharArr = secretWord.toCharArray();
int charCnt = secretWord.length();
for (int x = 0; triesCount < triesLimit; triesCount++) {
while (charCnt >= 0) {
System.out.println("Secrect Word :" + b.toString());
System.out.println("Guess a letter :");
char guessChar = scn.next().toCharArray()[0];
for (int i = 0; i < secrectStrCharArr.length; i++) {
if (guessChar == secrectStrCharArr[i]) {
b.setCharAt(i, guessChar);
correctCount++;
} else if (guessChar != secrectStrCharArr[i]) {
triesCount++;
System.out.println("Incorrect: " + triesCount);hangmanImage(triesCount,correctCount);
}
}
}
}
}
I tried looking it up on here but couldn't find setters and getters used in a sub/superclass
You need to create an instance of the class in the main method to access the variables and method available in that class like so
public class PlayHangman {
public static void main(String[] args) {
Hangman hangman = new Hangman();
hangman.setTriesLimit(2)
int value = hangman.getTriesLimit();
}
You can look into static keyword to access the value directly but that requires a bit more understanding of OOP's and JAVA.
This should work fine.
Hope it helps :)
EDITED
ToString method is just to convert everything in your model class to String which you have done correctly,but you have implemented incorrectly.... Change your ToString content so
#Override
public String toString() {
return ("The Secret Word you entered: " + this.getWord()
+ ".\n The max # of tries (Must be under 7): "
+ this.getTriesLimit());
}
You have initialized Scanner which does what you want, to ask the user to enter the values but again you haven't implemented it so add this to your main method
Scanner scn = new Scanner(System.in);
hangman.setTriesLimit(scn.nextInt());
hangman.setWord(scn.next());
hangman.toString()//Will work now
Trial and error is your best friend now :)
and Google some of the issues rather than waiting for an answer :)
Like rohit said, this is as simple as understand the basics of OOP, specific the encapsulation.
If you want to get a little deeper into OOP patterns, you could use the Observer pattern. This allows you to change the status of any class instance, even if they're not related by inheritance, aggregation, etc.
You can scale the solution by making List of Observer
Your observable interface
public interface IObservable {
// Set the observer
public void setObserver(IObserver iObserver);
// Notify the observer the current status
public void notifyObserver();
}
Your observer interface
public interface IObserver {
public void update(boolean status);
}
Your observer implementation
public class PlayHangman implements IObserver {
private boolean status = false;
public void printStatus() {
System.out.println("Status: " + (this.status ? "Win" : "Lose"));
}
#Override
public void update(boolean status) {
// The instance status is updated
this.status = status;
// Print the current status
this.printStatus();
}
}
Your observable implementation
public class Hangman implements IObservable{
private String goalWord = "";
private String currentWord = "";
private int triesLimit = 0;
private int tries = 0;
private IObserver iObserver;
public Hangman(String goalWord, int triesLimit) {
this.goalWord = goalWord;
this.triesLimit = triesLimit;
}
public void setCurrentWord(String currentWord) {
this.currentWord = currentWord;
this.notifyObserver();
}
public void addTry() {
this.tries++;
this.notifyObserver();
}
#Override
public void setObserver(IObserver iObserver) {
this.iObserver = iObserver;
}
#Override
public void notifyObserver() {
// True = win
this.iObserver.update(this.tries < this.triesLimit &&
this.goalWord.equals(this.currentWord));
}
}
Your Main class
public class Main{
public static void main(String[] args) {
// PlayHangman (game status)
PlayHangman playHangman = new PlayHangman();
// Hangman initializes with a goalWord and the triesLimit
Hangman hangman = new Hangman("HangmanJava", 5);
// Set the observer
hangman.setObserver(playHangman);
// During the game you just can set the current word and add a try
// You're not setting the status directly, that's the magic of the Observer pattern
hangman.setCurrentWord("Hang");
hangman.addTry();
hangman.setCurrentWord("HangmanJava");
}
}
Hope this helps and enjoy Java

2D array of objects returns null

Code creating object array and toString method.
import java.util.Arrays;
public class TicTacToeBoard extends BoardClass{
private int turns;
private XOClass[][] a;
public TicTacToeBoard(int rows,int cols){
super(rows,cols);
XOClass[][]a = new XOClass[rows][cols];
turns = 0;
}
public String toString(){
return (Arrays.deepToString(a));
}
}
Object Class
public class XOClass{
private String name;
private static int turn=0;
public XOClass(){
if (turn==0){
this.name = "-";
}
if (turn==1){
this.name = "X";
}
else{
this.name = "O";
}
}
Demo Class
public class play {
public static void main(String[] args){
TicTacToeBoard tac = new TicTacToeBoard(3,3);
System.out.println(tac);
}
}
when calling class play it returns null as there is nothing in the array what am I doing wrong with my code.
In your code:
XOClass[][]a = new XOClass[rows][cols];
You initialize new XOClass its only in the method and when the method end it is distrusting.
change that to
a = new XOClass[rows][cols];
This means you have created a two-dimensional array, with 'rows' rows. In the first row there are 'cols' columns.
and all rows are null.
Now you should create rows like :
a[0] = new XOClass[cols];
And then
a[0][0]=new XOClass();

I cannot pass a (String-)value to another class's setter method [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I know that i have not written a catch block yet.(reason?, but i think it's actually not the problem; the attributes of the "Game" class are perfectly changeable)
I always get an IOException when i try to call the setName method in Player (even if I set "name" in Player to public and change it directly).
public class game{
protected static int amountPlayers;
protected static Player[] playerList = new Player[amountPlayers];
public static void main (String[] args) throws IOException{
//Scanner reader = new Scanner(System.in);
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
String input;
System.out.println("new round? (1 for yes; enter for no):");
int boo = Integer.parseInt(br.readLine());
if (boo == 1) {
Rounds.setNew(true);
} // end of if
if (Rounds.getNew() == true) {
//SavingManagement.createFile();
System.out.println("# of players:");
int amount = Integer.parseInt(br.readLine());
setAmountPlayers(amount);
} // end of if
for (int i = 0; i < amountPlayers; i++) {
System.out.println("Name player No. " + (i + 1) + ":");
input = br.readLine();
playerList[i].setName(input);
} // end of for
}
public class Player {
protected static int score;
protected static String name = "";
public static void setName(String input) {
name = input;
}
}
Assuming that you are providing the valid size in amountPlayers, by writing the following statement you are just creating the Player array and not initializing it.
protected static int amountPlayers = 100;
/* This will just create the array */
protected static Player[] playerList = new Player[amountPlayers];
Before you can use setName(), you'll have to initialize the array as follows:
for(int x = 0; x < amountPlayers; x++) {
playerList[x] = new Player();
}
OR you can do something like this:
/* Create a new object of class Player */
Player myPlayer = new Player();
/* Set Name */
myPlayer.setName(input);
/* Assign it to your array */
playerList[i] = myPlayer;
Do you need the Player class as a public inner class?
Do you need to protoct the score and the Name?
Otherwise this should work:
public class game {
protected static int amountPlayers;
protected static Player[] playerList = new Player[amountPlayers];
public static void main(String[] args) throws IOException {
for (int i = 0; i < amountPlayers; i++) {
playerList[i].setName("test");
}
}
}
class Player {
private int score;
private String name = "";
public void setName(String input) {
name = input;
}
}
The PlayerList contains Player objects, so when you are calling the setName method like this: playerList[i].setName(input) it is through an instance of class Player, but the method is actually static and should be called in this way:
Player.setName()
Although, the best thing you could do is add a constructor in class Player, add new Player objects in the array playerList and make the method setName() and the other variables in class Player non-static.

how to use abstract classes, and implementing them

I'm not sure how eloquently I can really explain what I don't understand/need help with, I'm still Very new to Object Oriented Programming. This is regarding my coursework and I don't expect anyone to do it for me, I just need help understanding how to move on, and if I'm even on the right track.
Ok, so on to my question. Basically, I am attempting to create an arraylist which will hold a few objects which themselves has a bunch of information(obviously), my spec said to create an abstract class, which will be extended by my constructor class, which I did. The abstract class has a few variables (decided by spec) But I dont know how to move them over to my extended class.
I'll post my code below, and I hope it makes sense. I'd be very thankful for any help you all could provide. I'm very confused right now.
Basically, I would love to know, A) How do I create an object in my arraylist which will be able to contain everything in SportsClub and FootballClub, and preferably all the variables user inputted.
And B) I don't know how to print The object, When I print right now I get coursework.FootballClub#49233bdc, Which I'm sure there's a reason for but I need the information in the objects to display, E.g. name. And if possible to sort the results by alphabetical order with respect to name? I hope this is all written ok. Sorry and Thank you in advance.
package coursework;
import java.util.*;
/**
*
* #author w1469384
*/
public class PremierLeagueManager implements LeagueManager{
public static void main(String[] args) {
Scanner c1 = new Scanner(System.in);
Scanner c2 = new Scanner(System.in);
ArrayList<FootballClub> PL = new ArrayList<FootballClub>();
int choice;
System.out.println("Enter 1; To create a club, 2; To Delete a Club, 3; To display all clubs and 99 to close the program");
choice = c1.nextInt();
//Creates and adds a new FootballClub Object
while (choice != 99){
if (choice == 1){
System.out.println("Please Enter The games played for the club");
int played = c1.nextInt();
System.out.println("Please enter the number of wins");
int wins = c1.nextInt();
System.out.println("please enter the number of losses");
int losses = c1.nextInt();
System.out.println("please enter the number of draws");
int draws = c1.nextInt();
System.out.println("please enter the number of goals for");
int goalsFor = c1.nextInt();
System.out.println("please enter the number of goals against");
int goalsAgainst = c1.nextInt();
FootballClub club = new FootballClub(played, wins, losses, draws, goalsFor, goalsAgainst);
PL.add(club);
System.out.println("check");
}
//Deletes a FootballClub Object
if (choice == 2){
}
//Displays all Football Clubs in the PremierLeague array
if (choice == 3){
System.out.println(PL);
}
//Closes the Program 1
choice = c1.nextInt();
}
}
}
public abstract class SportsClub {
public String name;
public String location;
public int capacity;
public void setName(String Name){
name = Name;
}
public void setLocation(String Location){
location = Location;
}
public void setCapacity(int Capacity){
capacity = Capacity;
}
public String getName(){
return name;
}
public String getLocation(){
return location;
}
public int getCapacity(){
return capacity;
}
}
public class FootballClub extends SportsClub {
//Statistics for the club.
int played;
int wins;
int losses;
int draws;
int goalsFor;
int goalsAgainst;
public FootballClub(int gPlayed, int gWins, int gLosses, int gDraws, int gFor, int gAgainst){
played = gPlayed;
wins = gWins;
losses = gLosses;
draws = gDraws;
goalsFor = gFor;
goalsAgainst = gAgainst;
}
public void setPlayed(int newPlayed){
played = newPlayed;
}
public void setWins(int newWins){
wins = newWins;
}
public void setLosses(int newLosses){
losses = newLosses;
}
public void setDraws(int newDraws){
draws = newDraws;
}
public void setGoalsFor(int newGoalsFor){
goalsFor = newGoalsFor;
}
public void setGoalsAgainst(int newGoalsAgainst){
goalsAgainst = newGoalsAgainst;
}
public int getPlayed(){
return played;
}
public int getWins(){
return wins;
}
public int getLosses(){
return losses;
}
public int getDraws(){
return draws;
}
public int getGoalsFor(){
return goalsFor;
}
public int getGoalsAgainst(){
return goalsAgainst;
}
}
FootballClub inherits the variables declared in SportsClub so you can set them as you please.
public FootballClub(
int gPlayed, int gWins, int gLosses, int gDraws, int gFor, int gAgainst,
String inName, String inLocation, int inCapacity
) {
played = gPlayed;
wins = gWins;
losses = gLosses;
draws = gDraws;
goalsFor = gFor;
goalsAgainst = gAgainst;
// set the variables from the superclass
name = inName;
location = inLocation;
capacity = inCapacity;
}
FootballClub also inherits the methods declared in SportsClub so you can use the setters and getters too.
Normally you would create a constructor for SportsClub that sets these and then call that constructor from the FootballClub constructor.
// in SportsClub
protected SportsClub(
String inName, String inLocation, int inCapacity
) {
name = inName;
location = inLocation;
capacity = inCapacity;
}
// in FootballClub
public FootballClub(
int gPlayed, int gWins, int gLosses, int gDraws, int gFor, int gAgainst,
String inName, String inLocation, int inCapacity
) {
super(inName, inLocation, inCapacity);
played = gPlayed;
wins = gWins;
losses = gLosses;
draws = gDraws;
goalsFor = gFor;
goalsAgainst = gAgainst;
}
You should also make your member variables protected or private if you are using setters and getters.
I don't know how to print The object
You need to override toString. There is a short tutorial here.
Also unrelated side note: all Java variable identifiers should start with a lowercase letter.
When you have a method like this:
public void setName(String Name) { name = Name; }
It should be:
public void setName(String inName) { name = inName; }
Or:
public void setName(String name){ this.name = name; }

Categories

Resources