Null Pointer Exception in Text Game - java

I am making a simple text adventure game. I have a room class and an item class.
Each room has multiple items, and I am trying to make a method called addItem to store theitems in an ArrayList, but I get a NullPointerException when I try to add an item.
Room class
public class Room
{
private String description;
private HashMap<String, Room> exits;
private ArrayList<Item>items;
/**
* Create a room described "description". Initially, it has
* no exits. "description" is something like "a kitchen" or
* "an open court yard".
* #param description The room's description.
*/
public Room(String description)
{
this.description=description;
exits = new HashMap<String, Room>();
items = new ArrayList<Item>();
}
/**
* Define an exit from this room.
* #param direction The direction of the exit.
* #param neighbor The room to which the exit leads.
*/
public void setExit(String direction, Room neighbor)
{
exits.put(direction, neighbor);
}
/**
* #return The short description of the room
* (the one that was defined in the constructor).
*/
public String getShortDescription()
{
return description;
}
/**
* Return a description of the room in the form:
* You are in the kitchen.
* Exits: north west
* #return A long description of this room
*/
public String getLongDescription()
{
return "You are " + description + ".\n" + getExitString();
}
/**
* Return a string describing the room's exits, for example
* "Exits: north west".
* #return Details of the room's exits.
*/
private String getExitString()
{
String returnString = "Exits:";
Set<String> keys = exits.keySet();
for(String exit : keys) {
returnString += " " + exit;
}
return returnString;
}
/**
* Return the room that is reached if we go from this room in direction
* "direction". If there is no room in that direction, return null.
* #param direction The exit's direction.
* #return The room in the given direction.
*/
public Room getExit(String direction)
{
return exits.get(direction);
}
/**
* adds new item to the room
*/
public void addItem(String description)
{
Item Iitem = new Item(description);
items.add(Iitem);
}
}
Item Class
public class Item
{
private String description;
/**
* Constructor for objects of class Item
*/
public Item(String description)
{
this.description=description;
}
/**
* gets description of the item
*/
public String getDescription()
{
return description;
}
}

You never initialized items, so it's null.
items = new ArrayList<Item>();
Also I suggest you use interface for declaration, instead of a specific implementation
private Map<String, Room> exits; // stores exits of this room.
private List<Item> items;

You have not initialize the ArrayList<Item> items
You need to do:
ArrayList<Item> items = new ArrayList<Item>();

Related

How should i document the parameter "says"?

Can't resolve the problem :\ How i should document the second parameter "says"? Because SonarQube asking me about this again and again.
public class Dogs {
private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(Dogs.class);
private final String name;
private final String says;
/**
* The Dogs class.
*
* #param name
* says. // here the problem
*
*/
public Dogs(final String name, final String says) {
this.name = name;
this.says = says;
}
}
You should add #param in front of the param name, like this :
/**
* The Dogs class.
*
* #param name explain what is it !
* #param says explain what is it !
*
*/
public Dogs(final String name, final String says) {
this.name = name;
this.says = says;
}

Questions about calling a constructor and defining the variables in Java (Homework)

To be clear, this is an active homework assignment. I just need some guidance.
I am creating a bookstore program in Java that, in revision 1, only has to return information about one specific book when it runs. I must use two classes, and call the info in the secondary class inside the main method to output.
I think I created the constructor correctly inside the Book class, but what's the best way to A) define those variables and B) call the info inside the Bookstore class to output? I just need some guidance here, as I'm kinda stuck. Eclipse is asking me to re-define the int and double variables as a String, but they are going to be numbers...is there something in my syntax that is causing it to do that?
Here's what I have so far:
import java.util.Scanner; // Import Scanner
/** Main Class */
public class Bookstore {
/** Secondary Class */
private class Book {
/** Declare Variables */
private int isbn;
private String bookTitle;
private String authorName;
private int yearPublished;
private String publisherName;
private double bookPrice;
/** Constructor */
Book (int isbn, String bookTitle, String authorName, int yearPublished, String publisherName, double bookPrice) {
setIsbn(isbn);
setBookTitle(bookTitle);
setAuthorName(authorName);
setYearPublished(yearPublished);
setPublisherName(publisherName);
setBookPrice(bookPrice);
}
/**
* #return the isbn
*/
public void getIsbn(int isbn) {
return isbn;
}
/**
* #param isbn the isbn to set
*/
public void setIsbn(int isbn) {
this.isbn = isbn;
}
/**
* #return the bookTitle
*/
public void getBookTitle(String bookTitle) {
return bookTitle;
}
/**
* #param bookTitle the bookTitle to set
*/
public void setBookTitle(String bookTitle) {
this.bookTitle = bookTitle;
}
/**
* #return the authorName
*/
public String getAuthorName() {
return authorName;
}
/**
* #param authorName the authorName to set
*/
public void setAuthorName(String authorName) {
this.authorName = authorName;
}
/**
* #return the yearPublished
*/
public int getYearPublished() {
return yearPublished;
}
/**
* #param yearPublished the yearPublished to set
*/
public void setYearPublished(int yearPublished) {
this.yearPublished = yearPublished;
}
/**
* #return the publisherName
*/
public String getPublisherName() {
return publisherName;
}
/**
* #param publisherName the publisherName to set
*/
public void setPublisherName(String publisherName) {
this.publisherName = publisherName;
}
/**
* #return the bookPrice
*/
public double getBookPrice() {
return bookPrice;
}
/**
* #param bookPrice the bookPrice to set
*/
public void setBookPrice(double bookPrice) {
this.bookPrice = bookPrice;
}
} // End Book Class
/** Main Method */
public static void main(String[] args) {
} // End Main Method
} // End Bookstore Class
That's where I'm at. Again, I'm stuck on how to define the variables properly, and then call the data for output in the Bookstore method. I know how to print it to the screen, it's just getting it there that is perplexing me. Do I create another Book object inside the Bookstore class?
I appreciate any help that's available.
Let's start with...
private class Book {
I would say declaring an inner class as private might not be the best choice, as you not be able to use beyond the scope of BookStore, but that's a choice you need to make...
This...
/**
* #return the isbn
*/
public void getIsbn(int isbn) {
return isbn;
}
is wrong on a number of accounts. First, it is declared as void, meaning that the method won't return anything, but then you use return isbn within the method. It should be declared as returning an int.
Next, you pass isbn as a parameter to the method, but immediately return the same value, this isn't really what you want to do, you want to return the value of isbn defined by Book, for example...
/**
* #return the isbn
*/
public int getIsbn() {
return isbn;
}
The same thing goes for getBookTitle.
In some languages they pass parameters by reference, meaning you can actually alter the value in the method/function and that will be reflected in the callers context. Java doesn't do this (more accurately, you can't reassign the value within the method and have it reflected in the caller). This is tripping point for many developers.
Basically, this means you can't do something like...
public void getBookTitle(String bookTitle) {
bookTitle = this.bookTitle;
}
As the value of the parameter will the same in the callers context after the method call as it was before it. You have to "get" the value from the class.
An interesting side effect though, is you can change the properties of objects passed to a method, if they supply mutable functionality...

unable to instantiate class within method?

I am trying to instantiate an object from the following class:
public class Name {
//The unmodified name
private String name;
//The modified name
private String preprocessedName;
/**
* Constructor method which stores the original name in the name variable
* #param inputName
*/
public Name(String inputName){
//Store the name
this.name = inputName;
//Initialise the preProcessedName
this.preprocessedName = null;
}
/**
* Retrieves the original name
* #return the original name
*/
public String getName(){
return this.name;
}
/**
* Stores the preprocessed name in the preprocessedName variable
* #param the preprocessed name
*/
public void setPreprocessedName(String processedInput){
this.preprocessedName = processedInput;
}
/**
* Retrieves the preprocessed name
* #return the preprocessed name
*/
public String getpreprocessedName(){
return this.preprocessedName;
}
}
Within the following method:
/**
* Private method which instantiates names as a name object.
* #param names
*/
private void processInput(ArrayList<String> names){
library = new ArrayList<Name>();
for(String name : names){
Name tempName = new Name("r");
//Not bringing up any methods from the class
**strong text**tempName.**strong text**
//add to the library
library.add(tempName);
}
}
I am unable to use any methods from the Name class when I create the object, do you know why this is happening? e.g. it does not bring up the getters and setters from the class when I try auto completion.
Check the imports you have in the package.
Are you importing the correct Name class?

arrays and listview for android (java)

I am trying to show just the name of the player from the array into the list view. this is my code for that:
player_List.setAdapter(new ArrayAdapter<Player>(this, android.R.layout.simple_list_item_1, dataStore.getPlayers()));
im getting all the information from that array using this call. i am unsure how to just call the name.
this is the coding for my data store:
/**
* This class is essentially a global library for the Scoresheet.
* It provides methods through which the Players and Teams can be accessed
* from any part of the application.
* The saving/loading of application data will also be handled through this
* class.
*
* You can access this DataStore by calling:
* DataStore dataStore = ((DataStore)getApplicationContext());
* From any Activity
*/
public class DataStore extends Application {
// Create ArrayLists to hold all our Player and Team objects
private ArrayList<Player> players = new ArrayList<Player>();
private ArrayList<Team> teams = new ArrayList<Team>();
// File names for our internal storage:
private String playerFileName = "players";
private String teamFileName = "teams";
/**
* Add a Player object to the list of players.
* #param p The Player object to add
*/
public void addPlayer(Player p){
this.players.add(p);
}
/**
* Merge an ArrayList of Player objects with the current collection of Players
* #param players ArrayList of Player objects to add to the collection
*/
public void addPlayers(ArrayList<Player> players){
Iterator<Player> it = players.iterator();
while (it.hasNext()){
this.players.add(it.next());
}
}
/**
* Return an ArrayList of player objects containing all Players
* #return
*/
public ArrayList<Player> getPlayers(){
return this.players;
}
and this is my player class:
public class Player implements Serializable{
// Randomly generate serial ID
private static final long serialVersionUID = 7423594865734681292L;
private static int ID = 0; // Class variable
public String name;
private int id;
public Player(String name) throws Exception{
this.setId(ID);
ID++; // Increment class ID counter
if (!this.setName(name))
throw new Exception("Invalid Name"); // This is the only way to prevent the object being instantiated if it has an invalid name
}
public String getName() {
return name;
}
/**
* Set the players name as desired.
* #param name
* #return true on success, false on fail
*/
public boolean setName(String name) {
// Only update the name if we are actually given a string
boolean success = false;
name = name.trim();
if (!name.equals("")){
this.name = name;
success = true;
}
return success;
}
public int getId() {
return id;
}
private void setId(int id) {
this.id = id;
}
}
Use CustomAdapter and set in getView(...) method
Like,
Player player = getPlayers().get(position);
textview.setText(player.name)
see this example,,
http://www.softwarepassion.com/android-series-custom-listview-items-and-adapters/
http://jnastase.alner.net/archive/2010/12/19/custom-android-listadapter.aspx
I'm no expert on android listview, but if it just uses toString to decide what to show, implement toString to just return name:
public String toString() { return name; }

Java enum in practice, bad code to improve

I want to improve my use of JDK 1.5 and stop using private static final String instead of enum. This is what seems to be recommended.
But now my constant class looks like this :
public class CEnum{
/**
* #author JJA
* date : 20/10/2010
*/
public enum ListTypeAffichage {
DEP("DEPOT_TVA"), PAD("PAS_DEPOT_TVA"), NORM("CAT_NORMALE"), CAP("CAT_PARTICULIERE"), CAA("CAT_AUTRE_CAS");
private final String sName;
/**
* #param name String
*/
ListTypeAffichage(String name) {
this.sName = name;
}
/**
* #return String
*/
public String getType() {
return sName;
}
}
/**
* #author JJA
* date : 20/10/2010
*/
public enum ListTypeCategorie {
DEDUIRE("SOMME_A_DEDUIRE"), AJOUTER("SOMME_A_AJOUTER");
private final String sName;
/**
* #param name String
*/
ListTypeCategorie(String name) {
this.sName = name;
}
/**
* #return String
*/
public String getType() {
return sName;
}
}
/**
* #author JJA
* date : 26/10/2010
*/
public enum ListInterval {
POS("POSITIF"), NS("NON_SIGNE");
private final String sName;
/**
* #param name String
*/
ListInterval(String name) {
this.sName = name;
}
/**
* #return String
*/
public String getInterval() {
return sName;
}
}
}
instead of
public class ConstantesADMD {
public static final List<String> typeAffich = new ArrayList<String>();
...
ConstantesADMD(){
typeAffich.add("DEPOT_TVA");
typeAffich.add("PAS_DEPOT_TVA");
typeAffich.add("CAT_NORMALE");
...
}
}
My code seems to be really bad, but at least works. For each enum I have to add the redundant code :
private final String sName;
/**
* #param name String
*/
ListTypeAffichage(String name) {
this.sName = name;
}
/**
* #return String
*/
public String getType() {
return sName;
}
What improvment do you advise me?
Note : forget the last sentences of my first question, I need the index. Tell me if I have to post another question, editing my fisrt seems easier.
I would name my enum-constants as you have named your strings. You can then access the name using the Enum.toString() method. For example:
public enum ListTypeAffichage {
DEPOT_TVA, PAS_DEPOT_TVA, CAT_NORMALE, CAT_PARTICULIERE, CAT_AUTRE_CAS;
/**
* #return String
*/
public String getType() {
return toString();
}
}
You could of course also skip the getType() all together, and access the "type" using toString() instead:
ListTypeAffichage myEnum = ListTypeAffichage.CAT_PARTICULIRE;
System.out.println("Type: " + myEnum.toString()); // like this...
System.out.println("Type: " + myEnum); // ...or like this
According to the API, this is better than using the Enum.name() directly:
public final String name()
[...] Most programmers should use the toString() method in preference to this one [...]
Each enum has a name() method which return the exact string represantation of the constant. So you may do this:
public enum ListTypeAffichage {
DEPOT_TVA, PAS_DEPOT_TVA, CAT_NORMALE, CAT_PARTICULIERE, CAT_AUTRE_CAS
}
and then
ListTypeAffichage.DEPOT_TVA.name();
By using the abbreviations (DEP, PAD, NORM) etc. you have created aliases to (DEPOT_TVA, PAS_DEPOT_TVA, CAT_NORMALE) etc.
If you want to keep the abbreviations, then you'll have to maintain the enum as you have it.
If you are willing to do away with the abbreviations, then you can change you enum as below, I have included a main method in the enum to demonstrate its use.
public enum ListTypeAffichageNames {
DEPOT_TVA,
PAS_DEPOT_TVA,
CAT_NORMALE,
CAT_PARTICULIERE,
CAT_AUTRE_CAS;
public static void main(String[] args) {
System.out.println(DEPOT_TVA.toString());
ListTypeAffichageNames affichage = ListTypeAffichageNames.valueOf("DEPOT_TVA");
System.out.println(affichage.toString());
}
}
In addition to this, your current structure of constants does not give you compile time type checking, and does not prevent something like the following happening during runtime:
ConstantesADMD.typeAffich.clear();
// or
ConstantesADMD.typeAffich.remove("DEPOT_TVA");
ConstantesADMD.typeAffich.add("dEpOt-tVa");

Categories