JAVA Null pointer Exception getTitle method, I can't find it - java

There's no error while coding it, but when i ran it, it said
Exception in thread "main" java.lang.NullPointerException
at homework.Book.getTitle(Book.java:36)
at homework.BookMain.main(BookMain.java:61)
Java Result: 1
***********************************
package homework;
public class BookMain {
public static void main(String[] args){
int i;
int option;
Book[] bookSet = new Book[20];
bookSet[0] = new Book("I dare you","Joyce Meyer",2007);
bookSet[1] = new Book("Straight from the Heart","Rev. Fr. Mario Jose C. Ladra",2012);
bookSet[2] = new Book("Deliverance From Fear","Bob Buess",1993);
bookSet[3] = new Book("Extraordinary Book of Facts","Bathroom Readers' Institute",2006);
bookSet[4] = new Book("Fat Kid Rules the World","K.L. Going",2003);
Book.numberOfBooks = 5;
Book getter = new Book();
for (i=0; i<Book.numberOfBooks; i++)
{
System.out.println(getter.getTitle(bookSet[i])+" "+getter.getAuthor(bookSet[i])+" "+getter.getYear(bookSet[i]));
}
System.out.println();
for (i=0; i<Book.numberOfBooks; i++)
{
if(getter.getYear(bookSet[i])>2000)
System.out.println(getter.getTitle(bookSet[i])+" "+getter.getAuthor(bookSet[i])+" "+getter.getYear(bookSet[i]));
}
bookSet[5] = new Book("The Lake of Dead Languages","Carol Goodman",2002);
Shelf shelf1 = new Shelf("Shelf1","Bedroom");
Shelf shelf2 = new Shelf("Shelf2","Living room");
Shelf shelf3 = new Shelf("Shelf3","Basement");
Shelf placer = new Shelf();
placer.insertBook(shelf1,bookSet[1]);
placer.insertBook(shelf1,bookSet[2]);
placer.insertBook(shelf2,bookSet[3]);
placer.insertBook(shelf2,bookSet[4]);
placer.insertBook(shelf1,bookSet[5]);
placer.insertBook(shelf1,bookSet[0]);
System.out.println(placer.getShelfName(shelf1)+" "+placer.getLocation(shelf1));
Book aBookInShelf = new Book();
for(i=0; i<shelf1.booksInShelf; i++)
{
aBookInShelf = placer.pickBook(shelf1, i);
System.out.println(getter.getTitle(aBookInShelf)+" "+getter.getAuthor(aBookInShelf)
+" "+getter.getYear(aBookInShelf));
}
}
}
===========================================
Books class:
package homework;
public class Book {
private String title;
private String author;
private int year;
public static int numberOfBooks = 0;
public Book(String title, String author, int year){
this.title=title;
this.author=author;
this.year=year;
}
public Book(){
}
public String getAuthor(Book target){
return target.author;
}
public int getYear(Book target){
return target.year;
}
public String getTitle(Book target){
return target.title;
}
public static void main(String[] args){
}
}
=====================================
Shelves class:
package homework;
public class Shelf {
private String name;
private String location;
public static int booksInShelf=0;
private Book[] shelfBooks = new Book[20];
public Shelf(String name, String location){
this.name = name;
this.location = location;
}
public Shelf(){
}
public String getShelfName(Shelf target){
return target.name;
}
public String getLocation(Shelf target){
return target.location;
}
public void insertBook(Shelf target, Book aBook){
target.shelfBooks[target.booksInShelf] = aBook;
target.booksInShelf++;
}
public Book pickBook(Shelf target, int nthBook){
return target.shelfBooks[nthBook];
}
}

Beside getter/setter design madness it seems that NullPointerException is caused by fact that booksInShelf is static, which means that it belongs to entire Shelf class (instances of this class share value of this field) so when you add book to one Shelf and increment this field, it will be incremented for all instances of Shelf.
Because of that in loop
for(i=0; i<shelf1.booksInShelf; i++)
you are iterating even over positions that were not set yet and are still nulls. Now in
aBookInShelf = placer.pickBook(shelf1, i);
System.out.println(getter.getTitle(aBookInShelf)+" "+getter.getAuthor(aBookInShelf)
+" "+getter.getYear(aBookInShelf));
you are picking this null and using it inside getter.getTitle(null) which will try to invoke return null.title which will case NPE because null doesn't have title.
To fix this problem remove static modifier from booksInShelf field.

Related

Integer canno be derefrenced

I have some problem with my simple code in Java. I want to do aircraft flight search program, but when I leave the variable under the parameter, I get an error:
Airlines.java:14: error: int cannot be dereferenced
String Parameters = flightNumber_go.getParameters();
Anyone have any idea how I could solve this problem?
PS. Sorry for my bad English
import java.util.Scanner;
class Airlines{
public static void main(String args[]) throws Exception{
Flight 524 = new Flight("Moskwa", "Londyn", 140);
Flight 135 = new Flight("Warszawa", "Wroclaw", 60);
Flight 141 = new Flight("Frankfurt", "Rzym", 95);
Scanner flightNumber = new Scanner(System.in);
System.out.println("Enter code of your flight: ");
int flightNumber_go = Integer.valueOf(flightNumber.nextLine());
String Parameters = flightNumber_go.getParameters();
System.out.println(Parameters);
}
}
class Flight{
String departures;
String arrival;
int price;
public Flight(String departures, String arrival, int price){
this.departures = departures;
this.arrival = arrival;
this.price = price;
}
public String getParameters(String ... args){
return "Lot z "+this.departures+" do "+this.arrival+" kosztuje "+this.price;
}
}
To begin with you are misunderstanding how to correctly use an Object as getParameters will only work for the current object, it will not search all the objects you made. You must use a Collection to keep track on all of your objects if you want to find a specific one.
Additionally you should not use variable names to store information, instead store that information inside of the object as an integer.
Here is the modified Flight class:
class Flight {
private String departures;
private String arrival;
private int price;
private int flightNum;
public Flight(String departures, String arrival, int price, int flightNum){
this.departures = departures;
this.arrival = arrival;
this.price = price;
this.flightNum = flightNum;
}
public String getParameters(){
return "Lot z "+this.departures+" do "+this.arrival+" kosztuje "+this.price;
}
public String getDepartures() {
return departures;
}
public String getArrival() {
return arrival;
}
public int getPrice() {
return price;
}
public int getFlightNum() {
return flightNum;
}
public void setDepartures(String departures) {
this.departures = departures;
}
public void setArrival(String arrival) {
this.arrival = arrival;
}
public void setPrice(int price) {
this.price = price;
}
public void setFlightNum(int flightNum) {
this.flightNum = flightNum;
}
}
Note that I added the new parameter, flightNum and made all of your class variables private, with standard getters and setters for access.
Now here is the modified Airlines class that uses an ArrayList to store the Flights:
class Airlines {
public static void main(String args[]) throws Exception{
ArrayList<Flight> flights = new ArrayList<>();
flights.add(new Flight("Moskwa", "Londyn", 140, 524));
flights.add(new Flight("Warszawa", "Wroclaw", 60, 135));
flights.add(new Flight("Frankfurt", "Rzym", 95, 141));
Scanner flightNumber = new Scanner(System.in);
System.out.println("Enter code of your flight: ");
int flightNumber_go = Integer.valueOf(flightNumber.nextLine());
Flight currentFlight = findFlight(flights, flightNumber_go);
System.out.println(currentFlight.getParameters());
}
public static Flight findFlight(ArrayList<Flight> flights, int flightNum) {
for (Flight f : flights) {
if (f.getFlightNum() == flightNum) {
return f;
}
}
//If no flights are found
return null;
}
}
I added a static method called findFlight which takes in the ArrayList and flightNumber you want to find as a parameter, and returns the corresponding Flight. This is done using a simple enhanced for loop. The method will return null if no flight is found, which can modified to return whatever you want for a default case.
Example Run:
Enter code of your flight:
135
Lot z Warszawa do Wroclaw kosztuje 60
Note: It may make sense in your case to use a Map to store the key as the flight number with the Flight as the value which ensures the key is unique and then you do not need flightNumber in the Object itself. This ArrayList is just one way to do it.

The constructor Teacher(Teacher) is undefined

I am using a copy constructor and Inheritance in a class called 'Department' to call the information from class 'Teacher' which is a sub-class of 'Person'. After creating my set/get methods, I get the above error. Anyone have any insight as to why this is occurring?
Code from 'Department' class:
public class Department {
private String deptName;
private int numMajors;
private Teacher[] listTeachers; //inherits from Person class
private Student[] listStudents; //inherits from Person class
// First constructor for Department
public Department(String dn, int nm, Teacher[] listTeachers, Student[] listStudents) {
this.deptName = dn;
this.numMajors = nm;
this.listTeachers = new Teacher[listTeachers.length];
for (int i = 0; i < this.listTeachers.length; i++)
{
this.listTeachers[i] = new Teacher (listTeachers[i]);
}
//set method for Teachers Array
public void setListTeachers (Teacher[] other) {
this.listTeachers = new Teacher[other.length];
for (int i = 0; i < listTeachers.length; i++) {
this.listTeachers[i] = new Teacher (other[i]);
}
}
//get method for Teachers Array
public Teacher[] getListTeachers() {
Teacher[] copyTeachers = new Teacher[listTeachers.length];
for (int i = 0; i < copyTeachers.length; i++) {
copyTeachers[i] = new Teacher(this.listTeachers[i]);
}
return copyTeachers;
}
Here are the lines giving me errors:
1) this.listTeachers[i] = new Teacher (listTeachers[i]);
2) this.listTeachers[i] = new Teacher (other[i]);
3) copyTeachers[i] = new Teacher(this.listTeachers[i]);
Code from 'Teacher' class:
public class Teacher extends Person {
private String id;
private int salary;
private int num_yr_prof;
//Constructor for use in Teacher main method.
public Teacher(String n, int a, String s, boolean al, String i, int sal, int numyr) {
super(n, a, s, al);
this.id = i;
this.salary = sal;
this.num_yr_prof = numyr;
}
//Copy constructor for use in Department class.
public Teacher (String n, int a, String s, boolean al, Teacher other) {
super(n, a, s, al);
if (other == null) {
System.out.println("Fatal Error!");
System.exit(0);
}
this.id = other.id;
this.salary = other.salary;
this.num_yr_prof = other.num_yr_prof;
}
Your copy constructor might look like this:
public Teacher(Teacher teacher) {
this( teacher.n, teacher.a, teacher.s, teacher.al,
teacher.id, teacher.salary, teacher.num_yr_prof );
}
Since you do not show the code for the Person class, I have used the variable names n, a, s, and al here. They should be replaced by whatever those variables are named in the Person class. This, of course, assumes that those variables are either public or protected. If they are private, you need to use the getters for those variables (preferred even if they are public or protected).
You need to to your Teacher class a constructor that accepts a Teacher:
public Teacher(Teacher teacher) {
// do something
}

Array of Objects OutOfBoundsException [duplicate]

This question already has answers here:
Are fields initialized before constructor code is run in Java?
(5 answers)
Closed 7 years ago.
i'm (relative) new to java, i have some (minor) understanding of Arrays and Classes/Objects etc. But i can't find the solution to this Errors.
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at books$Bookshop.addBook(books.java:42)
at books.main(books.java:57)
My whole Code:
public class books {
static class Book{
private double price;
private String title;
private String isbn;
public Book(double price, String title, String isbn){
this.price = price;
this.title = title;
this.isbn = isbn;
}
public Book makeBook(double price, String title, String isbn){
Book new_book = new Book(price, title, isbn);
return new_book;
}
public String toString(){
String string = this.title + ", " + this.isbn + ", " + this.price;
return string;
}
}
static class Bookshop{
private int stock_max;
Book[] stock = new Book[stock_max];
private int book_counter;
public Bookshop(int size){
this.stock_max = size;
}
public void printBooks(){
for(int i=0; i<stock.length; i++){
System.out.println(stock[i].toString());
}
}
public void addBook(double p, String t, String i){
this.stock[book_counter] = new Book(p,t,i);
}
public void searchBook(String title){
for(int i=0; i<stock.length; i++){
if(title.equals(stock[i].title)){
System.out.println("Book in Stock");
}
}
}
}
public static void main(String[] args) {
Bookshop shop = new Bookshop(10);
shop.addBook(29.90, "title", "24578");
shop.addBook(19.59, "second", "12345");
shop.addBook(69.99, "third title", "47523");
shop.addBook(4.99, "title 4", "98789");
shop.printBooks();
shop.searchBook(args[0]);
}
}
I know that the ArrayIndexOutOfBoundsException means that it tries to make something at an index that doesnt exist. But i set the size of the bookshop to 10, and then add only 4 books to it (Error occurs at the first)...
private int stock_max;
Book[] stock = new Book[stock_max];
private int book_counter;
public Bookshop(int size){
this.stock_max = size;
}
This issue is that stock is set to new Book[stock_max] before the line this.stock_max = size, due to the way Java constructors and initialization is done. stock_max, like all uninitialized ints, starts at 0, so stock is set to an empty array. To fix this, just move the initialization inside the constructor:
private int stock_max;
Book[] stock;
private int book_counter;
public Bookshop(int size){
this.stock_max = size;
this.stock = new Book[stock_max];
}

Add objects with random variables using a loop

I am trying to write a program where I ask to the user how many persons he wants to implement in this world. Afterwards, I would like as many person objects as the user answered. I defined a person class with a person constructor containing all person variables ( + getters/setters). After this, I tried to create a loop to assign values to my variables (most of them happen random). Currently, I set the number of instances I want to create to 20 (arbitrary).
This is my person class
public class Person implements Item {
public static final int MAX_AGE = 70;
public static final int MAX_SEX_APPEAL = 10;
public static final int MAX_AGRESSION_LEVEL = 10;
public static final int MAX_STRENGTH = 10;
private int id;
private int age;
private boolean gender;
private int sexAppeal;
private int agressionLevel;
private int strength;
private boolean isAlive;
public Person (int id, int age, boolean gender, int sexAppeal, int agressionLevel, int strength, boolean isAlive){
this.setId(id);
this.setAge(age);
this.setGender(gender);
this.setSexAppeal(sexAppeal);
this.setAgressionLevel(agressionLevel);
this.setStrength(strength);
this.setAlive(isAlive);
}
void getBorn () {
isAlive = true;
age = 0;
// a new people is born
// age = 0
// other variables: random
}
void die () {
isAlive = false;
// people die when they reach the max age
// people die when being on the same cell as vulcanos
// people can be murdered
// setAlive = false
}
void murder () {
// when 2 people with min agression level on the same land ==> weakest one dies
}
void move () {
// method to make people move
// random (only to adjucant fields)
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public boolean isGender() {
return gender;
}
public void setGender(boolean gender) {
this.gender = gender;
}
public int getSexAppeal() {
return sexAppeal;
}
public void setSexAppeal(int sexAppeal) {
this.sexAppeal = sexAppeal;
}
public int getAgressionLevel() {
return agressionLevel;
}
public void setAgressionLevel(int agressionLevel) {
this.agressionLevel = agressionLevel;
}
public int getStrength() {
return strength;
}
public void setStrength(int strength) {
this.strength = strength;
}
public boolean isAlive() {
return isAlive;
}
public void setAlive(boolean isAlive) {
this.isAlive = isAlive;
}
}
And this is my "test class" where I try to create 20 instances :
import java.util.concurrent.ThreadLocalRandom;
public class test {
public static void main(String[] args) {
for (int i = 0; i < 20; i ++) {
Person person(i) = new Person();
person.setId(i);
person.setAge(ThreadLocalRandom.current().nextInt(0, Person.MAX_AGE + 1));
person.setGender((Math.random() < 0.5));
person.setSexAppeal(ThreadLocalRandom.current().nextInt(0, Person.MAX_SEX_APPEAL + 1));
person.setAgressionLevel(ThreadLocalRandom.current().nextInt(0, Person.MAX_SEX_APPEAL + 1));
person.setStrength(ThreadLocalRandom.current().nextInt(0, Person.MAX_SEX_APPEAL + 1));
person.setAlive(true);
}
}
}
However, I am getting the following error at this line
Person person(i) = new Person();
The constructor Person () is undefined
Type mismatch: cannot convert from Person to int
I understand those errors but I don't know another way to become to the result I want to achieve
You should make a list and just add the created persons to it.
public class test {
public static void main(String[] args) {
List<Person> persons = new ArrayList<>(); // create a list to store the generated persons
for (int i = 0; i < 20; i++) {
Person person = new Person(); // generate a person
person.setId(i);
person.setAge(ThreadLocalRandom.current().nextInt(0, Person.MAX_AGE + 1));
person.setGender((Math.random() < 0.5));
person.setSexAppeal(ThreadLocalRandom.current().nextInt(0, Person.MAX_SEX_APPEAL + 1));
person.setAgressionLevel(ThreadLocalRandom.current().nextInt(0, Person.MAX_SEX_APPEAL + 1));
person.setStrength(ThreadLocalRandom.current().nextInt(0, Person.MAX_SEX_APPEAL + 1));
person.setAlive(true);
persons.add(person); /// add the generated person to the list
}
}
}
Also if you want to call the Person constructor without parameters the class must have a constructor that takes no parameters.
public Person() {}

fixing nullpointerexception error in java

here is my code. i keep getting a nullpointerexception in my sort and print method, it starts on the line with the for loop with allAnimals.length. I think the array allAnimal in the class, isnt filled in getData as it should. allAnimal in getData method isnt being treated as allAnimal in the class. Basically all other methods still think allAnimal is null. I am no master in java so if someone could please tell me how to fix this error, or give me tips on how to avoid it I would greatly appreciate it.
public class Animal {
//data fields
private String name;
private int birthYear;
private String species;
private float balance;
private String ownersName;
static Animal[] allAnimal;
public Animal(){
//no-arg constructor
}
public Animal(String name, int birthYear, String species, float balance, String ownersName){
// constructor builds animal template
this.name = name;
this.birthYear = birthYear;
this.species = species;
this.balance = balance;
this.ownersName = ownersName;
}
//set and get for name
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
//set and get for birth year
public int getBirthYear() {
return birthYear;
}
public void setBirthYear(int birthYear) {
this.birthYear = birthYear;
}
//set and get for species
public String getSpecies() {
return species;
}
public void setSpecies(String species) {
this.species = species;
}
//set and get for balance
public float getBalance() {
return balance;
}
public void setBalance(float balance) {
this.balance = balance;
}
//set and get for owner
public String getOwnersName() {
return ownersName;
}
public void setOwnersName(String ownersName) {
this.ownersName = ownersName;
}
public static void getData(){
System.out.println("How many animals are in this report? ");
Scanner kb = new Scanner(System.in);
int length = kb.nextInt();
Animal[] allAnimal = new Animal[length];
System.out.println("input: animal name, birth year, species, bill balance and owner's name.");
//fill array of objects with data
int i;
for(i = 0; i < allAnimal.length; i++){
allAnimal[i] = new Animal(kb.next(), kb.nextInt(), kb.next(), kb.nextFloat(), kb.next());
}
}//end getData
public static void sortData(Animal[] allAnimal){
Animal temp;
int i,j;
for(i = 0; i < allAnimal.length; i++){
for(j = i + 1; j < allAnimal.length; j++){
if(allAnimal[i].getBalance() > allAnimal[j].getBalance() ){ //swap big with small
temp = allAnimal[j];
allAnimal[j] = allAnimal[i];
allAnimal[i] = temp;
}
}
}
}//end sortData
public static void printData(Animal[] allAnimal){
int i;
for(i = 0; i < allAnimal.length; i++){
System.out.println("Pet Name: " + allAnimal[i].getName() + " Birth year: " +
allAnimal[i].getBirthYear() + " Species: " + allAnimal[i].getSpecies() +
" Balance due: " + allAnimal[i].getBalance() + " Owner: " + allAnimal[i].getOwnersName());
}
}
public static void main(String[] args){
getData();
sortData(allAnimal);
printData(allAnimal);
}//end main
}//end class
You have two variables named allAnimal:
static Animal[] allAnimal;
Animal[] allAnimal = new Animal[length];
You initialize one and then use the other (which is still null).
In getData(), change
Animal[] allAnimal = new Animal[length];
to
allAnimal = new Animal[length];
There could be other problems, I didn't look too closely.
You are creating local variable Animal[] allAnimal within getData() method that caused the problem.
Problem here
public static void getData(){
Animal[] allAnimal = new Animal[length]; //here is the problem
}
fix it like below.
public static void getData(){
allAnimal = new Animal[length]; //here is the fix
}
You have only declared AllAnimal at the class level :
static Animal[] allAnimal;
Now, in your method getData() you have declared and initialized a local variable allAnimal. Note that it has nothing to do with the one at class level.
Animal[] allAnimal = new Animal[length];
In other methods you are trying to use class level allAnimal which will throw a null pointer inless it is initiatlized.
for(i = 0; i < allAnimal.length; i++){

Categories