adding objects to an ArrayList using an abstract class - java

I'm trying to add animal objects to a pet ArrayList using an accept method but I am getting an error saying cannot find symbol. I've been over it a bunch of times and am just not seeing it.
Thanks for your help.
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Scanner;
public class Shelter2 implements AnimalShelter {
private ArrayList<Animal2> pet;
private int Id;
Scanner in = new Scanner(System.in);
public Shelter2() {
pet = new ArrayList<Animal2>();
SimpleDateFormat DateFormat = new SimpleDateFormat("MM-dd-yyyy");
Date now = new Date();
String today = DateFormat.format(now).toString();
// pet.add(new Cat("Snow White", "Domestic Short Hair", "White", "F",
// "01-01-2012", null));
// pet.add(new Dog("Buster", "Beagle", "Brown/White/Black", "male",
// "12-25-2011", null));
// pet.add(new Reptile("Jack", "Lizard", "01-31-2012", null));
}
public String allAnimals() {
String str = "";
for (Animal2 p : pet) {
str = str + p + "\n\n";
}
return str;
}
public String available() {
String str = "";
for (int i = 0; i < pet.size(); i++) {
Animal2 p = pet.get(i);
if (p.getAdoptedDate() == null) {
str = str + p + "\n\n";
}
}
return str;
}
public String adopted() {
String str = "";
for (int i = 0; i < pet.size(); i++) {
Animal2 p = pet.get(i);
if (p.getAdoptedDate() != null) {
str = str + p + "\n\n";
}
}
return str;
}
public boolean adopt(int id) {
return true;
}
public boolean accept(Animal2 pet) {
String type = null;
System.out.println("What type of animal? (Cat, Dog, Reptile)");
type = in.next();
if (type == "Cat") {
System.out.println("Enter name: ");
String name = in.next();
System.out.println("Enter description: ");
String desc = in.next();
System.out.println("Enter color: ");
String color = in.next();
System.out.println("Enter sex: ");
String sex = in.next();
pet.add(new Cat(name, desc, color, sex, null, null));
}
return true;
}
}
public abstract class Animal2 {
public String name;
public String arrivalDate;
public String adoptedDate;
public String getName() {
return new String(name);
}
public void setName(String name) {
this.name = name;
}
public String getArrivalDate() {
return new String(arrivalDate);
}
public void setArrivalDate(String arrivalDate) {
this.arrivalDate = arrivalDate;
}
public String getAdoptedDate() {
return adoptedDate;
}
public void setAdoptedDate(String adoptedDate) {
this.adoptedDate = adoptedDate;
}
#Override
public String toString() {
return "\nName: " + name + "\nArrival Date: " + arrivalDate
+ "\nAdopted Date: " + adoptedDate;
}
}
class Cat extends Animal2 {
String desc;
String color;
String sex;
char s;
Cat(String name, String desc, String color, String sex, String arrivalDate,
String adoptedDate) {
super.setName(name);
super.setArrivalDate(arrivalDate);
super.setAdoptedDate(adoptedDate);
setDesc(desc);
setColor(color);
setSex(sex);
char s = ' ';
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
s = sex.toLowerCase().charAt(0);
if ((s == 'f') || (s == 'm')) {
this.sex = sex;
} else {
System.err.println("Illegal value for Cat sex field - " + sex);
}
}
#Override
public String toString() {
if (s == 'f') {
sex = "Female";
} else if (s == 'm') {
sex = "Male";
} else {
sex = null;
}
return "\nCat: " + super.toString() + "\nDescription: " + desc
+ "\nColor: " + color + "\nSex: " + sex;
}
}
class Dog extends Animal2 {
String bred;
String color;
String sex;
char s;
Dog(String name, String bred, String color, String sex, String arrivalDate,
String adoptedDate) {
super.setName(name);
super.setArrivalDate(arrivalDate);
super.setAdoptedDate(adoptedDate);
setBred(bred);
setColor(color);
setSex(sex);
char s = ' ';
}
public String getBred() {
return bred;
}
public void setBred(String bred) {
this.bred = bred;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
s = sex.toLowerCase().charAt(0);
if ((s == 'f') || (s == 'm')) {
this.sex = sex;
} else {
System.err.println("Illegal value for Dog sex field - " + sex);
}
}
#Override
public String toString() {
if (s == 'f') {
sex = "Female";
} else if (s == 'm') {
sex = "Male";
} else {
sex = null;
}
return "Dog: " + super.toString() + "\nBred: " + bred + "\nColor: "
+ color + "\nSex: " + sex;
}
}
class Reptile extends Animal2 {
String type;
Reptile(String name, String type, String arrivalDate, String adoptedDate) {
super.setName(name);
super.setArrivalDate(arrivalDate);
super.setAdoptedDate(adoptedDate);
setType(type);
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
#Override
public String toString() {
return "Reptile: " + super.toString() + "\nType: " + type;
}
}

I'm going to go out on a limb here and say that this line is giving you the error:
pet.add(new Cat(name, desc, color, sex, null, null));
You're getting this error because pet, within the scope of your accept method, is an Animal2. If you want to reference the field named pet, try:
this.pet.add(new Cat(name, desc, color, sex, null, null));
Also, in your Dog and Cat classes, you are not setting s. You are creating a new variable s and setting it to ' ' (char s = ' ';). I'm not sure how that will affect your project, but you probably aren't intending to do it.

Related

How can I use subclass in java that I can print two different length of String?

Here is a big project, so I can just show you part of the code.
There are two different plan of membership: standard and family. When the member is standard membership, the information of that member contains(name, dob, expire date, location), but when the member's plan is family, the information of that member contains(name, dob, expire date, location, guest-pass remaining) Which means their gonna have one more element. But they have been stored in the same database. And my question is how can I print them.
The out put should be
Carl Brown, DOB: 10/7/1991, Membership expires 3/31/2023, Location: PISCATAWAY, 08854, MIDDLESEX
Jerry Brown, DOB: 6/30/1979, Membership expires 12/28/2022, Location: EDISON, 08837, MIDDLESEX, (Family) guest-pass remaining: 1
But I only get
Carl Brown, DOB: 10/7/1991, Membership expires 3/31/2023, Location: PISCATAWAY, 08854, MIDDLESEX
Jerry Brown, DOB: 6/30/1979, Membership expires 12/28/2022, Location: EDISON, 08837, MIDDLESEX
Here is my code
Member
public class Member implements Comparable<Member> {
private String fname;
private String lname;
private Date dob;
private Location location;
private Date expire = Date.getEXP();
#Override
public String toString() {
String info = String.format("%s %s, DOB: %s, Membership expires %s, Location: %s", fname, lname, dob,
expire, location);
return info;
}
public Member(String fname, String lname, Date dob, Location location) {
this.fname = fname;
this.lname = lname;
this.dob = dob;
this.location = location;
}
public String getFname() {
return fname;
}
public String getLname() {
return lname;
}
public Date getDOB() {
return dob;
}
public Date getEXP() {
return expire;
}
public Location getLocation() {
return location;
}
}
And it asked me to use subclass to get a Family plan,so I write this
Family
public class Family extends Member{
private int gpRemaining;
public Family(String fname, String lname, Date dob, Location location, int gpRemaining) {
super(fname, lname, dob, location);
this.gpRemaining = gpRemaining;
}
#Override
public String toString() {
String info = String.format("%s %s, DOB: %s, Membership expires %s, Location: %s, (Family) " +
"guest-pass remaining:" + " %d", this.getFname(), this.getLname(), this.getDOB(),
this.getEXP(), this.getLocation(), gpRemaining);
return info;
}
public int getGpRemaining() {
return gpRemaining;
}
}
And here is the MemberDatabase print method:
public class MemberDatabase {
private Member[] mlist;
private int size = 0;
private int capacity = 4;
public MemberDatabase() {
mlist = new Member[capacity];
}
public int getSize() {
return size;
}
private int find(Member member) {
for (int indexOfMember = 0; indexOfMember < size; indexOfMember++) {
if(mlist[indexOfMember].equals(member)) {
return indexOfMember;
}
}
return -1;
}
private void grow() {
capacity += 4;
mlist = Arrays.copyOf(mlist, capacity);
}
public boolean add(Member member) {
if (find(member) != -1) {
return false;
} else {
if (size >= capacity) {
return false;
}
if (size != 0 && (find(member) != -1)) {
return false;
}
mlist[size++] = member;
if (size >= capacity) {
grow();
}
return true;
}
}
public boolean remove(Member member) {
if (member == null) {
return false;
}
int indexOfMember = find(member);
if (indexOfMember != -1) {
mlist[indexOfMember] = mlist[--size];
mlist[size] = null;
return true;
}
return false;
}
/**
* Print the original membership database
*/
public void print() {
if (size == 0) {
System.out.println("Member database is empty!");
return;
}
System.out.println("\n-list of members-");
for (int i = 0; i < size; i++) {
System.out.println(mlist[i]);
}
System.out.println("-end of list-\n");
}
Here is the addmethod which Add the members:
The input is like
A Carl Brown, 10/7/1991, Piscataway
AF Jerry Brown 6/30/1979 Edison
case A means this member has standard membership which means the
output should be
> Carl Brown, DOB: 10/7/1991, Membership expires 3/31/2023, Location: PISCATAWAY, 08854, MIDDLESEX
public void run() {
System.out.println("Gym Manager running...");
String input;
String[] inputs;
creatClass();
while (scan.hasNext()) {
input = scan.nextLine();
inputs = input.split("\\s");
if (input.length() == 0) {
System.out.println();
continue;
}
switch (inputs[0]) {
case "A" -> A(inputs);
case "AF" -> AF(inputs);
private void A(String[] input) {
String[] dobDate = input[3].split("/");
Date dob = new Date(Integer.parseInt(dobDate[0]), Integer.parseInt(dobDate[1]), Integer.parseInt(dobDate[2]));
if (isValidLocation(input[4])) {
if (isValidDOB(dob)) {
Member member = new Member(input[1], input[2], dob, Location.valueOf(input[4].toUpperCase()));
if (member !=null) {
if (!database.add(member)) {
System.out.println(input[1] + " " + input[2] + " is already in the database.");
} else System.out.println(input[1] + " " + input[2] + " added.");
}
}
}
}
/**
Case AP means that the member has family membership and the output should be
Jerry Brown, DOB: 6/30/1979, Membership expires 12/28/2022, Location: EDISON, 08837, MIDDLESEX, (Family) guest-pass remaining: 1
*/
private void AP (String[] input) {
String[] dobDate = input[3].split("/");
Date dob = new Date(Integer.parseInt(dobDate[0]), Integer.parseInt(dobDate[1]), Integer.parseInt(dobDate[2]));
if (isValidLocation(input[4])) {
if (isValidDOB(dob)) {
Family member = new Family(input[1], input[2], dob, Location.valueOf(input[4].toUpperCase()), 1);
if (member !=null) {
if (!database.add(member)) {
System.out.println(input[1] + " " + input[2] + " is already in the database.");
} else System.out.println(input[1] + " " + input[2] + " added.");
}
}
}
}
Please help!!

Pass a created object from one class to another and add to ArrayList?

I´ve created a function where you add a result for a participant in a event.
Now I want to pass the created object to an addResult-method in my participant class and thereafter add it to an ArrayList in the same class, but I can´t really figure out how to do this. I´ve been stuck on this for a while, and could need some help how to approach this further.
This is what I´ve coded so far for this:
public Participant getParticipant() {
int startNumber = readInt();
boolean participantFound = false;
for (int i = 0; i < allParticipants.size(); i++) {
if (allParticipants.get(i).getStartNumber() == (startNumber)) {
participantFound = true;
return allParticipants.get(i);
}
}
if (!participantFound) {
System.out.println("No participant with number " + startNumber + " exists. " + "\n");
runCommandLoop();
}
return null;
}
public Event getEvent() {
String eventName = norm();
boolean eventFound = false;
for (int a = 0; a < allEvents.size(); a++) {
if (allEvents.get(a).getEventName().equalsIgnoreCase(eventName)) {
eventFound = true;
return allEvents.get(a);
}
}
if (!eventFound) {
System.out.println("No event called " + eventName + " found! ");
runCommandLoop();
}
else {
System.out.println("To many attempts! ");
runCommandLoop();
}
return null;
}
public void addResult() {
System.out.println("Number: ");
Participant p = getParticipant();
if (p == null) {
}
System.out.println("Event: ");
Event e = getEvent();
if (e == null) {
}
System.out.println("Type in the result for " + p.getFirstName() + " " + p.getLastName() + " in "
+ e.getEventName() + ": ");
double result = readDouble();
while (result < 0) {
System.out.println("Must be greater than or equal to zero! Try again: ");
result = readDouble();
}
Result r = new Result();
**// THIS IS WHERE I´M STUCK RIGHT NOW**
r.addResult();
System.out.println("The result " + result + " is now registred");
}
And this is my Participant class:
import java.util.ArrayList;
public class Participant {
public ArrayList<Result> allResults = new ArrayList<>();
private String firstName;
private String lastName;
private String team;
private int startNumber;
public Participant(String firstName, String lastName, String team, int startNumber) {
this.firstName = firstName;
this.lastName = lastName;
this.team = team;
this.startNumber = startNumber;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getTeam() {
return team;
}
public void setTeam(String team) {
this.team = team;
}
public int getStartNumber() {
return startNumber;
}
public void setStartNumber(int startNumber) {
this.startNumber = startNumber;
}
public void addResult(Result r) {
allResults.add(r);
}
public String toString() {
return "\n" + "Name: " + firstName + "\n" + "Last name: " + lastName + "\n" + "Team: " + team + "\n"
+ "Start number: " + startNumber;
}
}
And my Result class:
public class Result {
private double result;
public Result(double result) {
this.result = result;
}
public double getResult() {
return result;
}
public void setResult(double result) {
this.result = result;
}
public void printResult() {
System.out.println(result);
}
}
What you are doing is
Result r = new Result();
**// THIS IS WHERE I´M STUCK RIGHT NOW**
r.addResult();
but I do not see addResult() Method in Result Class. What you need to do is
p.addResult(r); // p is your Participant
hope this helps

Accessing array list methods from another class

I have two classes I want to use together. An array list class and a Text User Interface class which will call methods from the array list class in order to complete tasks.
Whenever I try to call methods with parameters in my array list class from my TUI class, it gives me an error.
I'm trying to access an (add) method in my arrayList class from a TUI class, which will add a user to my arrayList. Can somebody please tell me how to fix this. The method that is returning the error is the 'public void addBorrower()' at the bottom of my TUI class.
My two classes are below in full.
This is my TUI class.
import java.util.ArrayList;
import java.util.Scanner;
public class BorrowerTUI
{
private BorrowerList borrowerList;
private Scanner myScanner;
public BorrowerTUI()
{
myScanner = new Scanner(System.in);
BorrowerList borrowerList = new BorrowerList();
}
public void menu()
{
int command = -1;
while (command != 0)
{
displayMenu();
command = getCommand();
execute (command);
}
}
private void displayMenu()
{
System.out.println( "Options are" );
System.out.println( "Enter 1" );
System.out.println( "Enter 2" );
System.out.println( "Enter 3" );
System.out.println( "Enter 4" );
}
private void execute( int command)
{
if ( command == 1)
addBorrower();
else
if ( command == 2 )
getNumberOfBorrowers();
else
if ( command == 3)
quitCommand();
else
if ( command == 4)
quitCommand();
else
if ( command == 5)
quitCommand();
else
System.out.println("Unknown Command");
}
private int getCommand()
{
System.out.print ("Enter command: ");
int command = myScanner.nextInt();
myScanner.nextLine();
return command;
}
public void getNumberOfBorrowers()
{
int command = myScanner.nextInt();
System.out.println("We have" + borrowerList.getNumberOfBorrowers() + "borrowers");
}
public void quitCommand()
{
int command = myScanner.nextInt();
System.out.println("Application Closing");
System.exit(0);
}
public void addBorrower()
{
borrowerList.addBorrower(Borrower borrower);
}
}
This is my array list class.
import java.util.ArrayList;
public class BorrowerList
{
private ArrayList<Borrower> borrowers;
public BorrowerList()
{
borrowers = new ArrayList<Borrower>();
}
public void addBorrower(Borrower borrower)
{
borrowers.add(borrower);
}
public int getNumberOfBorrowers()
{
return borrowers.size();
}
public boolean getBorrower(String libraryNumber)
{
for(Borrower borrower : borrowers)
borrower.getLibraryNumber();
return true;
}
public void getBorrower(int borrowerEntry)
{
if (borrowerEntry < 0)
{
System.out.println("Negative entry: " + borrowerEntry);
}
else if (borrowerEntry < getNumberOfBorrowers())
{
Borrower borrower = borrowers.get(borrowerEntry);
borrower.printBorrowerDetails();
}
else
{
System.out.println("No such entry: " + borrowerEntry);
}
}
public void getAllBorrowers()
{
for(Borrower borrower : borrowers)
{
borrower.printBorrowerDetails();
System.out.println();
}
}
public void removeBorrower(int borrowerEntry)
{
if(borrowerEntry < 0)
{
System.out.println("Negative entry :" + borrowerEntry);
}
else if(borrowerEntry < getNumberOfBorrowers())
{
borrowers.remove(borrowerEntry);
}
else
{
System.out.println("No such entry :" + borrowerEntry);
}
}
public boolean removeBorrower(String libraryNumber)
{
int index = 0;
for (Borrower borrower: borrowers)
{
if (libraryNumber.equals(borrower.getLibraryNumber()))
{
borrowers.remove(index);
return true;
}
index++;
}
return false;
}
public int search(String libraryNumber)
{
int index = 0;
for (Borrower borrower : borrowers)
{
if (libraryNumber.equals(borrower.getLibraryNumber()))
{
return index;
}
else
{
index++;
}
}
return -1;
}
}
Borrower Class:
public class Borrower
{
private String firstName;
private String lastName;
private String libraryNumber;
private int noOfBooks;
private Address address;
public Borrower(String fName, String lName, String lNumber,
String street, String town, String postcode)
{
firstName = fName;
lastName = lName;
libraryNumber = lNumber;
noOfBooks = 1;
address = new Address(street, town, postcode);
}
public Borrower(String fName, String lName, String lNumber, int numberOfBooks,
String street, String town, String postcode)
{
firstName = fName;
lastName = lName;
libraryNumber = lNumber;
noOfBooks = numberOfBooks;
address = new Address(street, town, postcode);
}
public String getFirstName()
{
return firstName;
}
public String getLastName()
{
return lastName;
}
public String getLibraryNumber()
{
return libraryNumber;
}
public int getNoOfBooks()
{
return noOfBooks;
}
public void printBorrowerDetails()
{
System.out.println( firstName + " " + lastName
+ "\n" + address.getFullAddress()
+ "\nLibrary Number: " + libraryNumber
+ "\nNumber of loans: " + noOfBooks);
}
public void borrowBook()
{
noOfBooks = noOfBooks + 1;
System.out.println("Books on loan: " + noOfBooks);
}
public void borrowBooks(int number)
{
noOfBooks = noOfBooks + number;
System.out.println("Books on loan: " + noOfBooks);
}
public void returnBook ()
{
noOfBooks = noOfBooks - 1 ;
System.out.println("Books on loan: " + noOfBooks);
}
public String getAddress()
{
return address.getFullAddress();
}
public void setAddress(String street, String town, String postcode)
{
address.setFullAddress(street, town, postcode);
}
public void printAddress()
{
address.printAddress();
}
} // end class

arraylist sorting alphabetically

i have gotten the assignment to make a phonebook with 3 classes, the driver that runs it all, phonebook,and a person class.
the problem i was having was i couldn't make the Collection.sort(telbook.personen)
get to work as how i have it in my code, what i want to know is what do i have to add or replace to make it sort the arraylist
as i have it now as a function that i can run by myself to check if it did sort, but that didn't work.
driver class:
/**
* Created by ricardo on 2/26/2015.
*/
import java.util.*;
public class Driver {
Phonebook telbook = new Phonebook();
Scanner scan = new Scanner(System.in);
String newLine = System.getProperty("line.separator");
String[] Commands = {"/addperson - add a person to my beautiful program",
"/listpersons - for full list of persons",
"/removeperson - to remove a made person",
"/sortlist - sorts the phonebook (alphabetically)"};
private boolean running;
private boolean startmessage = false;
public static void main(String[] args) {
Driver n = new Driver();
n.run();
}
public void run() {
running = true;
startProgram();
}
public void startProgram() {
while (running) {
if (!startmessage) {
System.out.println("Type /commands for all available commands.");
startmessage = true;
}
String entered = scan.nextLine();
if (entered.equals("/commands")) {
for (int i = 0; i < Commands.length; i++)
System.out.println(Commands[i]);
} else if (entered.equals("/addperson")) {
addPerson();
} else if (entered.equals("/listpersons")) {
listPersons();
} else if (entered.equals("/removeperson")) {
removePerson();
} else if (entered.equals("/sortlist")) {
sortList();
} else {
System.out.println("Command not available. Type /commands for full list of commands");
}
}
}
public void addPerson() {
System.out.println("Fill in your name");
String addname = scan.nextLine();
System.out.println("Fill in your adress");
String addadress = scan.nextLine();
System.out.println("Fill in your city");
String addcity = scan.nextLine();
System.out.println("Fill in your phonenumber");
String addphonenumber = scan.nextLine();
System.out.println("Your data has been saved!");
Person addperson = new Person(addname, addadress, addphonenumber, addcity);
telbook.personen.add(addperson);
//sortList();
}
public void removePerson() {
listPersons();
System.out.println("Insert the ID of the person to be removed");
int ID = Integer.parseInt(scan.nextLine());
if (ID > telbook.personen.size()) {
System.out.println("There is no person with this ID, please select a different ID");
removePerson();
} else {
telbook.personen.remove(ID);
System.out.println("Person with the ID of " + ID + " has been removed");
}
}
public void listPersons() {
int ID = 0;
if (telbook.personen.isEmpty()) {
System.out.println("There is no person added yet. type /addperson to do so");
}
for (int i = 0; i < telbook.personen.size(); i++) {
System.out.println("ID:" + ID + newLine + " name: " + telbook.personen.get(i).name + newLine + " adress: " + telbook.personen.get(i).adress + newLine + " city: " + telbook.personen.get(i).city + newLine + " phonenumber: " + telbook.personen.get(i).phonenumber);
ID++;
}
}
public void sortList() {
Collections.sort(telbook.personen);
}
}
phonebook class:
/**
* Created by ricardo on 2/26/2015.
*/
import java.util.*;
public class Phonebook {
ArrayList<Person> personen = new ArrayList<Person>();
}
person class:
/**
* Created by ricardo on 2/26/2015.
*/
public class Person {
String name, adress, phonenumber, city;
public Person(String name, String adress, String phonenumber, String city) {
this.name = name;
this.adress = adress;
this.city = city;
this.phonenumber = phonenumber;
}
// public String getCity() { return city; }
//
// public void setCity(String city) {
// this.city = city;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getAdress() {
// return adress;
// }
//
// public void setAdress(String adress) {
// this.adress = adress;
// }
//
// public String getPhonenumber() {
// return phonenumber;
// }
//
// public void setPhonenumber(String phonenumber) {
// this.phonenumber = phonenumber;
// }
}
You should make your Person class implement the Comparable interface, and specifically tell how one should compare two Person objects.
An alternative is to implement a Comparator, and use Collections.sort(arrayList,comparator)

Fixing null pointer exceptions in Java (with ArrayList) [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Java null pointer exceptions - don't understand why…
MOVIE.JAVA
package javaPractical.week3;
import javax.swing.*;
public class Movie {
// private attributes
private String title;
private String movieURL;
private String year;
private String genre;
private String actor;
// constructor
Movie(String t, String u, String y, String g, String a) {
this.title = t;
this.movieURL = u;
this.year = y;
this.genre = g;
this.actor = a;
}
// getters and setters
public void setTitle(String t) {
this.title = t;
}
public String getTitle() {
return this.title;
}
public void set_url(String a) {
this.movieURL = a;
}
public String get_url() {
return this.movieURL;
}
public void setYear(String y) {
this.year = y;
}
public String getYear() {
return this.year;
}
public void setGenre(String g) {
this.genre = g;
}
public String getGenre() {
return this.genre;
}
public void setActor(String a) {
this.actor = a;
}
public String getActor() {
return this.actor;
}
// output movie details
public String toString() {
return ("Title: " + this.title + "\nURL: " + this.movieURL + "\nYear: "
+ this.year + "\nGenre: " + this.genre + "\nActor: " + this.actor);
}
public static void main(String[] args) {
// testing Movie class
Movie Movie1 = new Movie("Spiderman", "www.", "2002", "Action",
"Tobey M");
JOptionPane.showMessageDialog(null, Movie1.toString());
// testing MovieList class
}
}
MOVIELIST.JAVA
package javaPractical.week3;
import javax.swing.*;
import java.util.ArrayList;
public class MovieList1 {
private static ArrayList<Movie> myFavouriteMovies = new ArrayList();
private static int NUM_OF_MOVIES = 10;
private int numberOfMovies = 0;
private int index = 0;
public MovieList1() {
this.myFavouriteMovies = null;
this.numberOfMovies = 0;
this.index = 0;
}
public int getNumberOfMovies() {
return this.myFavouriteMovies.size();
}
public boolean isEmpty() {
if (this.myFavouriteMovies.isEmpty()) {
return true;
} else
return false;
}
public static void main(String[] args) {
MovieList1 List = new MovieList1();
String titleADD;
String movieURLADD;
String yearADD;
String genreADD;
String actorADD;
titleADD = JOptionPane.showInputDialog(null, "Enter title:");
movieURLADD = JOptionPane.showInputDialog(null, "Enter URL:");
yearADD = JOptionPane.showInputDialog(null, "Enter year:");
genreADD = JOptionPane.showInputDialog(null, "Enter genre:");
actorADD = JOptionPane.showInputDialog(null, "Enter actor:");
Movie TempMovie = new Movie(titleADD, movieURLADD, yearADD, genreADD,
actorADD);
// crashes here
myFavouriteMovies.add(TempMovie);
}
}
You have defined static attribute private static ArrayList<Movie> myFavouriteMovies = new ArrayList();
But in the constructor you are assigning the null. After that you are invoking calls like myFavouriteMovies.size() which causes NullPointerException
public MovieList1() {
this.myFavouriteMovies = null;
this.numberOfMovies = 0;
this.index = 0;
}
Of course it crashes - you've set it to null.
Why on earth didn't you heed the perfectly good advice you received here?
Java null pointer exceptions - don't understand why
You're wasting everyone's time on a trivial question. I'm voting to close.
Try this - it's still heinous, but it runs:
package javaPractical.week3;
import javax.swing.*;
import java.util.ArrayList;
import java.util.List;
public class MovieList1
{
private static int NUM_OF_MOVIES = 10;
private List<Movie> myFavouriteMovies;
private int numberOfMovies = 0;
private int index = 0;
public MovieList1()
{
this.myFavouriteMovies = new ArrayList<Movie>();
this.numberOfMovies = 0;
this.index = 0;
}
public int getNumberOfMovies()
{
return this.myFavouriteMovies.size();
}
public boolean isEmpty()
{
return this.myFavouriteMovies.isEmpty();
}
public void add(Movie movie)
{
this.myFavouriteMovies.add(movie);
}
#Override
public String toString()
{
return "MovieList1{" +
"myFavouriteMovies=" + myFavouriteMovies +
'}';
}
public static void main(String[] args)
{
MovieList1 movieList = new MovieList1();
String titleADD;
String movieURLADD;
String yearADD;
String genreADD;
String actorADD;
titleADD = JOptionPane.showInputDialog(null, "Enter title:");
movieURLADD = JOptionPane.showInputDialog(null, "Enter URL:");
yearADD = JOptionPane.showInputDialog(null, "Enter year:");
genreADD = JOptionPane.showInputDialog(null, "Enter genre:");
actorADD = JOptionPane.showInputDialog(null, "Enter actor:");
Movie TempMovie = new Movie(titleADD, movieURLADD, yearADD, genreADD,
actorADD);
// crashes here
movieList.add(TempMovie);
System.out.println(movieList);
}
}
class Movie
{
private String title;
private String url;
private String year;
private String genre;
private String actor;
Movie(String title, String url, String year, String genre, String actor)
{
this.title = title;
this.url = url;
this.year = year;
this.genre = genre;
this.actor = actor;
}
#Override
public String toString()
{
return "Movie{" +
"title='" + title + '\'' +
", url='" + url + '\'' +
", year='" + year + '\'' +
", genre='" + genre + '\'' +
", actor='" + actor + '\'' +
'}';
}
}

Categories

Resources