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++){
Related
import java.util.ArrayList;
class BryanList{
public static void main (String [] args)
{
ArrayList<String> alist=new ArrayList<String>();
alist.add("Bryan");
alist.add("18");
alist.add("Chicken Rice");
for (int i = 0; i <= alist.size(); i++) {
System.out.println ("My Name: "+alist.get(i));
System.out.println ("Age: "+alist.get(i));
System.out.println ("Favourite food: "+alist.get(i));
}
}
}
How come its not just displaying just one output instead there's 3 of the same output? Does anyone have any solution for this? Thanks.
If you want one time output then use generics class structure.
Create one class which you want to save records.
class Menu {
public int age;
public String name;
public String favFood;
}
You can create getter/setter method if you need. Otherwise just declare variables with public keyword.
Create one ArrayList which will store object of Menu class.
ArrayList<Menu> alist = new ArrayList<Menu>();
Menu menu = new Menu();
menu.name = "Bryan";
menu.age = 18;
menu.favFood = "Chicken Rice";
alist.add(menu);
Print output
for (int i = 0; i <= alist.size(); i++) {
Menu menu = alist.get(i);
System.out.println("My Name: " + menu.name);
System.out.println("Age: " + menu.age);
System.out.println("Favourite food: " + menu.favFood);
}
I updated your class with your requirement, please check.
class BryanList {
public static void main(String[] args) {
ArrayList<Menu> alist = new ArrayList<Menu>();
Menu menu = new Menu();
menu.name = "Bryan";
menu.age = 18;
menu.favFood = "Chicken Rice";
alist.add(menu);
for (int i = 0; i <= alist.size(); i++) {
Menu menu = alist.get(i);
System.out.println("My Name: " + menu.name);
System.out.println("Age: " + menu.age);
System.out.println("Favourite food: " + menu.favFood);
}
}
}
class Menu {
public int age;
public String name;
public String favFood;
}
Happy coding :)
Your loop check is happening on alist.size() which is in your case 3.
Now, in each iteration, it's printing alist.get(i) 3 times.
Suggestion:
Use POJO and add it to your list.
public class Person{
String name;
int age;
String favFood;
public getName(){
return name;
}
public getAge(){
return age;
}
public getFavFood(){
return favFood;
}
public setName(String name){
this.name = name;
}
public setName(int age){
this.age = age;
}
public setName(String favFood){
this.favFood = favFood;
}
}
And now, your code will work with simple modification.
public static void main (String [] args){
ArrayList<String> alist=new ArrayList<String>();
Person person = new Person();
person.setName("Bryan");
person.setAge(18);
person.setFavFood("Chicken Rice");
// If you want multiple person to add, you need to use loops, and that way you can keep creating person objects and add them to list.
// Suggesting, use separate method for that logic.
alist.add(person);
for (int i = 0; i <= alist.size(); i++) {
Person p = alist.get(i);
System.out.println ("My Name: "+ p.getName());
System.out.println ("Age: "+ p.getAge());
System.out.println ("Favourite food: "+ p.getFavFood());
}
}
Because your printing codes in a For loop. And loop is running 3 three times
alist.size()
means 3, you have 3 item in that list.
This can be your object class:
public class Table {
int age;
String name;
String food;
public Table(int age, String name, String food) {
this.age = age;
this.name = name;
this.food = food;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getFood() {
return food;
}
public void setFood(String food) {
this.food = food;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
And fill arraylist with your object:
public static void main(String[] args) {
ArrayList<Table> alist = new ArrayList<>();
// this is how you fill
alist.add(new Table(18, "Bryan", "Rice");
for (int i = 0; i <= alist.size(); i++) {
System.out.println("AGE: " + alist.get(i).age);
//other stuff
}
}
import java.util.ArrayList;
public class HelloWorld {
public static void main(String []args) {
ArrayList<String> alist_name=new ArrayList<String>();
ArrayList<String> alist_value=new ArrayList<String>();
alist_name.add("My Name: ");
alist_name.add("Age: ");
alist_name.add("Favourite food: ");
alist_value.add("Bryan");
alist_value.add("18");
alist_value.add("Chicken Rice");
for (int i = 0; i < alist_name.size(); i++) {
System.out.println (alist_name.get(i)+alist_value.get(i));
}
}
}
I've implemented the interface comparable and the method compareTo(). I have a list named randomHumans that contains 10 objects. 5 objects with three fields: name, age and year they started studying, and 5 objects with two fields: name and age. I would like to sort my list, and tried using:
Collections.sort(randomHumans);
This gave me the following error message:
The method sort(List<T>) in the type Collections is not applicable for the arguments (ArrayList<Object>)
I then tried this code:
Collections.sort((List<T>) randomObjects);
But it just gives me two new error messages. Maybe I need to specify what field it should sort after, but I can't find how to implement this. Any help would be greatly appreciated.
main method:
public static void main (String[] args) {
ArrayList<Object> randomObjects = new ArrayList<Object>();
for (int j=0; j<5; j++) {
Fysiker randomFysiker = new Fysiker();
randomObjects.add(randomFysiker);
Human randomHuman = new Human();
randomObjects.add(randomHuman);
}
System.out.println(randomObjects.toString());
//Collections.sort(randomObjects);
}
Human class:
class Human implements Comparable<Human> {
int age;
String name;
public Human (int myAge, String myName) {
name = myName;
age = myAge;
}
public Human() {
this(randomAge(),randomName());
}
public int compareTo(Human o) {
return this.age - o.age;
}
protected static int randomAge() {
Random randomGenerator = new Random();
return randomGenerator.nextInt(100);
}
protected static String randomName() {
Random randomGenerator = new Random();
return "Name"+randomGenerator.nextInt(15);
}
public int getAge(){
return age;
}
public String getName() {
return name;
}
public String toString() {
return "\nName: " + name + "\nAge: " + age + " yrs old\n";
}
}
Fysiker class:
public class Fysiker extends Human {
int year;
public Fysiker(int myAge2, String myName2, int myYear) {
name = myName2;
year = myYear+1932;
if (myAge2 >= 15+(2017-myYear)) {
age = myAge2;
} else {
age = 15+(2017-year);
}
}
public Fysiker() {
this(randomAge(),randomName(), randomYear());
}
protected static int randomYear() {
Random randomGenerator = new Random();
return randomGenerator.nextInt(83);
}
public int getYear(){
return year;
}
public String toString() {
return "\nName: " + name + "\nAge: " + age + " yrs old" + "\nStarted Physics: " + year+"\n";
}
}
Just change the generic parameter from Object to Human
public static void main (String[] args) {
List<Human> randomObjects = new ArrayList<>();
for (int j = 0; j < 5; j++) {
Fysiker randomFysiker = new Fysiker();
randomObjects.add(randomFysiker);
Human randomHuman = new Human();
randomObjects.add(randomHuman);
}
System.out.println(randomObjects);
Collections.sort(randomObjects);
}
When you write Collections.sort(randomHumans); randomHumans must be a List of Comparable. If you are 'forced' to use a List of Object, you must give a Comparator to explain how to compare each object :
Collections.sort(randomHumans, humanComparator);
It's all explained in the offcial documentation :
sort(java.util.List)
sort(java.util.List, java.util.Comparator)
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() {}
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.
I have no idea why our professor is making us do this weird printing but its for our final, its due in an hour, and ive been trying to get it to run forever and I cant get anywhere. So i have four classes, MyWord, Section, Page and Newspaper. MyWord is just Myword. Section contains Section and MyWord. Page includes Section, Page, and MyWord. Newspaper contains them all. I have a main method that just prints off the info you type in. Here is the only example provided. All of my code is included from the classes to show I've actually done work and need help. thank you.
Word[] w = new Word[3]; //example
w[0] = new Word(“hello”);
w[1] = new Word(“bob”);
w[2] = new Word(“smith”);
Section s = new Section(w, 20);
s.print();
//the above call to print should print off the following or something
//very similar to the following:
//Section 20: hello bob smith
my classes are also here
public class MyWord
{
private String word;
public MyWord(){ //constructor
word = "";
}
public MyWord(String word){ //using this keyword to assign word
this.word=word;
}
public String getWord(){ //accessor
return word;
}
public void setWord(String word){ //mutator
this.word=word;
}
public void print(){
System.out.print(word);
}
}
public class Section
{
private MyWord[] words; //taking in MyWord
private int sectionNumber;
public Section(){ //default constructor
words = new MyWord[0];
sectionNumber = 0;
}
public Section(MyWord[] m, int num){ //constructor
words = m;
sectionNumber = num;
}
public int getSectionNumber(){ //accessor
return sectionNumber;
}
public void setSectionNumber(int num){ //mutator
sectionNumber = num;
}
public MyWord[] getWords(){ //accessor
return words;
}
public void setWords(MyWord[] m){ //mutator
words = m;
}
public void print(){
System.out.print("Section " + sectionNumber + ": ");
for(int i =0; i <words.length; i++){
words[i].print();
System.out.print(" ");
}
}
}
public class Page
{
private Section[] sections; //taking in other class
private int pageNumber;
public Page(){ //setting defaults
sections = new Section[0];
pageNumber = 0;
}
public Page(Section[] m, int num){ //passing in sections[]
sections = m;
pageNumber = num;
}
public int getPageNumber(){ //accessor
return pageNumber;
}
public void setPageNumber(int num){ //mutator
pageNumber = num;
}
public Section[] getSections(){ //accessor
return sections;
}
public void setSections(Section[] m){ //mutator
sections = m;
}
public void print(){
System.out.print("Page " + pageNumber + ": ");
for(int i =0; i <sections.length; i++){
sections[i].print();
System.out.print(" ");
}
System.out.println(" ");
}
}
public class Newspaper
{
private Page[] pages; //taking in Page[]
private String title;
private double price;
public Newspaper(){
pages = new Page[0];
title = "Comp Sci Newspaper"; //default title
price = 2.50; //default price
}
public Newspaper(Page[] m, double num, String t){
pages = m;
price = num; //assigning values
title = t;
}
public String getTitle(){ //accessor
return title;
}
public void setTitle(String t){ //mutator
title = t;
}
public Page[] getPages(){ //accessor
return pages;
}
public void setPages(Page[] m){ //mutator
pages = m;
}
public double getPrice(){ //accessor
return price;
}
public void setPrice(double num){ //mutator
price = num;
}
public void print(){
System.out.print("Newspaper " + title + " " + "Price: " + price);
for(int i =0; i <pages.length; i++){
pages[i].print();
System.out.print(" ");
}
System.out.println(" ");
}
}
I think you should be making your array as MyWord not Word, so :
MyWord[] w = new MyWord[3];
Then as far as I can see it might work? Can you say what happens when you try to run / compile it?