Run time binding in java using interfaces - java

// Item class
import java.io.*;
interface Item {
void read();
void show();
}
class Book implements Item {
String name,author,publication;
public void read() {
Console con = System.console();
System.out.println("Enter Name of the Book:");
name = con.readLine();
System.out.println("Enter Author Name:");
author = con.readLine();
System.out.println("Enter Publication of the book:");
publication = con.readLine();
}
public void show() {
System.out.println("List Of Issued Items");
System.out.println("Name :"+name);
System.out.println("Author :"+author);
System.out.println("Publication :"+publication);
}
}
class Dvd implements Item {
String dname,director,category;
public void read() {
Console con = System.console();
System.out.println("Enter Name of the dvd ");
dname = con.readLine();
System.out.println("Enter Director Name");
director = con.readLine();
System.out.println("Enter Category of the dvd: ");
category = con.readLine();
}
public void show() {
System.out.println("List Of Issued Items");
System.out.println("Name :"+dname);
System.out.println("Director :"+director);
System.out.println("Category :"+category);
}
}
Library class
import java.io.*;
class Library {
public static void main(String args[]) {
Console con = System.console();
Item arr[] = new Item[2];
Item a;
for(int i=0;i<arr.length;i++) {
System.out.println("Enter Your Choice : < b / d >");
String ch = con.readLine();
switch(ch) {
case "b":
a = new Book();
a.read();
a.show();
break;
case "d":
a = new Dvd();
a.read();
a.show();
break;
default:
System.out.println(" You Enetred The Wrong Choice !!!");
}
}
}
}
As in this code i have created two classes i.e.. Item and Libraryy .
At run time dynamic binding is done successfully but after reading any choice it shows results at the same time and i want to show all results after entering all the choices first .
For storing references i used arrays which stores the refernce of my choice types.

**//Class Item is Fine **
import java.io.*;
interface Item {
void read();
void show();
}
class Book implements Item {
String name,author,publication;
public void read() {
Console con = System.console();
System.out.println("Enter Name of the Book:");
name = con.readLine();
System.out.println("Enter Author Name:");
author = con.readLine();
System.out.println("Enter Publication of the book:");
publication = con.readLine();
}
public void show() {
System.out.println("List Of Issued Items");
System.out.println("Name :"+name);
System.out.println("Author :"+author);
System.out.println("Publication :"+publication);
}
}
class Dvd implements Item {
String dname,director,category;
public void read() {
Console con = System.console();
System.out.println("Enter Name of the dvd ");
dname = con.readLine();
System.out.println("Enter Director Name");
director = con.readLine();
System.out.println("Enter Category of the dvd: ");
category = con.readLine();
}
public void show() {
System.out.println("List Of Issued Items");
System.out.println("Name :"+dname);
System.out.println("Director :"+director);
System.out.println("Category :"+category);
}
}
// Class Library
import java.io.*;
class Library {
public static void main(String args[]) {
Console con = System.console();
Item arr[] = new Item[2];
Item a;
for(int i=0;i<arr.length;i++)
{
System.out.println("Enter Your Choice : < b / d >");
String ch = con.readLine();
switch(ch)
{
case "b":
arr[i] = new Book();
arr[i].read();
break;
case "d":
arr[i] = new Dvd();
arr[i].read();
break;
default:
System.out.println(" You Enetred The Wrong Choice !!!");
}
}
for(int i=0;i<arr.length;i++)
arr[i].show();
}
}

Related

HashMap returning null after adding values

I know this question has been asked before but I can't understand how to fix this issue. I'm adding values to a HashMap and in setStudent and then when I try to change the value in replaceName but the key doesn't seem to exist.
import java.util.*;
public class Student {
private HashMap<String, List<String>> studentDetails = new HashMap<String, List<String>>();
private HashMap<String, List<String>> studentModules = new HashMap<String, List<String>>();
public void setStudent(String id, String name, String postalAddress, String emailAddress, String degreeTitle, String dateEnrolled, List<String> modules) {
List<String> information = new ArrayList<>();
information.add(name);
information.add(postalAddress);
information.add(emailAddress);
information.add(degreeTitle);
information.add(dateEnrolled);
studentDetails.put(id, information);
studentModules.put(id, modules);
}
public List<String> getStudentDetails(String x) {
return studentDetails.get(x);
}
public List<String> getStudentModules(String x) {
return studentModules.get(x);
}
public void replaceName(String id, String name, String postalAddress, String emailAddress, String degreeTitle, String dateEnrolled) {
List<String> information = new ArrayList<>();
information.add(name);
information.add(postalAddress);
information.add(emailAddress);
information.add(degreeTitle);
information.add(dateEnrolled);
studentDetails.replace(id, information);
}
}
My main class is quite long but basically it takes user input to get the values:
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner source = new Scanner(System.in);
RecordManager r = new RecordManager();
Module m = new Module();
Student s = new Student();
ChangeName c = new ChangeName();
while (true) {
System.out.println("Please enter the student id:");
r.setId(source.nextLine());
System.out.println("Please enter the student name:");
r.setName(source.nextLine());
System.out.println("Please enter the student address:");
r.setAddress(source.nextLine());
System.out.println("Please enter the student email address:");
r.setEmailAddress(source.nextLine());
System.out.println("Please enter the degree title:");
r.setDegreeTitle(source.nextLine());
System.out.println("Please enter the date enrolled:");
r.setDateEnrolled(source.nextLine());
List<String> a = new ArrayList<>();
while (true) {
System.out.println("Please enter the module name:");
String name = source.nextLine();
m.setName(name);
a = r.addModule(name, a);
m.setTitle(name);
System.out.println("Please enter the module code:");
m.setCode(source.nextLine());
while (true) {
System.out.println("Please enter the module mark (between 1 and 100):");
int mark = source.nextInt();
if (mark > 0 && mark <101) {
m.setMark(mark);
break;
}
else {
System.out.println("Module mark must be between 1 and 100");
}
}
System.out.println("Please enter the module credits:");
m.setCredits(source.nextInt());
m.setModule();
System.out.println("Would you like to enter another module? (Y/N)");
String more = source.next();
if (more.equalsIgnoreCase("N")) {
break;
}
source.nextLine();
}
r.setModules(a);
s.setStudent(r.getId(), r.getName(), r.getAddress(), r.getEmailAddress(), r.getDegreeTitle(), r.getDateEnrolled(), r.getModules());
r.addStudents(r.getId(), s.getStudentDetails(r.getId()));
System.out.println("Would you like to enter the details for another student? (Y/N)");
String another = source.next();
if (another.equalsIgnoreCase("N")) {
break;
}
source.nextLine();
}
while (true) {
System.out.println("Full list of students and details (1) \nLookup a student by name (2) \nChange student name (3)");
source.nextLine();
int choice = source.nextInt();
if (choice == 1) {
for (String id : r.getStudents().keySet()) {
System.out.println(s.getStudentDetails(id) + " " + s.getStudentModules(id));
}
break;
}
else if (choice == 2) {
System.out.println("Please enter the full name of the student:");
source.nextLine();
String name = source.nextLine();
boolean exists = false;
int i = 0;
for (String id : r.getStudents().keySet()) {
if (s.getStudentDetails(id).get(i).equalsIgnoreCase(name)) {
System.out.println(s.getStudentDetails(id) + " " + s.getStudentModules(id));
exists = true;
}
i += 1;
}
if (exists == false) {
System.out.println("Student not found");
}
break;
}
else if (choice == 3) {
System.out.println("Please enter the ID of the student:");
source.nextLine();
String id = source.nextLine();
System.out.println("Please enter the new name:");
String name = source.nextLine();
c.changeName(id, name, s.getStudentDetails(id));
System.out.println(s.getStudentDetails(id));
break;
}
else {
System.out.println("Incorrect selection. Please enter 1, 2 or 3");
}
}
}
}
And finally I have the class to change the name:
import java.util.*;
public class ChangeName {
RecordManager r = new RecordManager();
Student s = new Student();
public void changeName(String id, String newName, List<String> details) {
s.replaceName(id, newName, details.get(1), details.get(2), details.get(3), details.get(4));
}
}
Any help would be greatly appreciated!!

ArrayLists (Removing and Changing Elements)

Hello everyone I am an amateur in Java and had some specific questions about a program using ArrayLists. The program is made up of several classes, and its purpose is to add, change, remove, and display friends from a Phone Book. I have the add and display methods done, but I'm having trouble with the remove and change method. I saw a similar case on this site, but it did not help me solve my problems. Any help at all would be much appreciated. This is what I have so far:
package bestfriends;
import java.util.Scanner;
import java.util.ArrayList;
public class BFFHelper
{
ArrayList<BestFriends> myBFFs;
Scanner keyboard = new Scanner(System.in);
public BFFHelper()
{
myBFFs = new ArrayList<BestFriends>();
}
public void addABFF()
{
System.out.println("Enter a first name: ");
String firstName = keyboard.next();
System.out.println("Enter a last name: ");
String lastName = keyboard.next();
System.out.println("Enter a nick name: ");
String nickName = keyboard.next();
System.out.println("Enter a phone number: ");
String cellPhone = keyboard.next();
BestFriends aBFF = new BestFriends(firstName, lastName, nickName, cellPhone);
myBFFs.add(aBFF);
}
public void changeABFF()
{
System.out.println("I am in changeBFF");
}
public void displayABFF()
{
System.out.println("My Best Friends Phonebook is: ");
System.out.println(myBFFs);
}
public void removeABFF()
{
System.out.print("Enter a friend's name to be removed: ");
int i = 0;
boolean found = false;
while (i < myBFFs.size() && !found)
{
if(firstName.equalsIgnoreCase(myBFFs.get(i).getFirstName()) && lastName.equalsIgnoreCase(myBFFs.get(i).getLastName()))
{
found = true;
}
else
i++;
}
}
}
That was my Helper Class, for which I'm having trouble with the removeABFF method, and still need to create a changeABFF method from scratch. Next is my main class:
package bestfriends;
import java.util.Scanner;
public class BFFPhoneBook
{
public static void main(String args[])
{
int menuOption = 0;
Scanner keyboard = new Scanner(System.in);
BFFHelper myHelper = new BFFHelper();
do
{
System.out.println("1. Add a Friend");
System.out.println("2. Change a Friend");
System.out.println("3. Remove a Friend");
System.out.println("4. Display a Friend");
System.out.println("5. Exit");
System.out.print("Enter your selection: ");
menuOption = keyboard.nextInt();
switch (menuOption)
{
case 1:
myHelper.addABFF();
break;
case 2:
myHelper.changeABFF();
break;
case 3:
myHelper.removeABFF();
break;
case 4:
myHelper.displayABFF();
break;
case 5:
break;
default:
System.out.println("Invalid option. Enter 1 - 5");
}
} while (menuOption != 5);
}
}
This is my last class:
package bestfriends;
public class BestFriends {
private static int friendNumber = 0;
private int friendIdNumber;
String firstName;
private String lastName;
private String nickName;
private String cellPhoneNumber;
public BestFriends (String aFirstName, String aLastName, String aNickName, String aCellPhone)
{
firstName = aFirstName;
lastName = aLastName;
nickName = aNickName;
cellPhoneNumber = aCellPhone;
friendIdNumber = ++friendNumber;
// friendIdNumber = friendNumber++;
}
public boolean equals(Object aFriend)
{
if (aFriend instanceof BestFriends )
{
BestFriends myFriend = (BestFriends) aFriend;
if (lastName.equals(myFriend.lastName) && firstName.equals(myFriend.firstName))
return true;
else
return false;
}
else
return false;
}
public String getFirstName()
{
return firstName;
}
public String getLastName()
{
return lastName;
}
public String getNickName()
{
return nickName;
}
public String getCellPhone()
{
return cellPhoneNumber;
}
public int getFriendId()
{
return friendIdNumber;
}
public String toString()
{
return friendIdNumber + ". " + firstName + " (" + nickName + ") " + lastName + "\n" + cellPhoneNumber + "\n";
}
}
To explore and manipulate a arraylist an iterator is used
the object lacks the Setters
declare variables
ArrayList<BestFriends> myBFFs;
Scanner keyboard = new Scanner(System.in);
BestFriends best;
public BFFHelper()
{
myBFFs = new ArrayList<BestFriends>();
best= new BestFriends();
}
Delete
public void removeABFF()
{
System.out.print("Enter a friend's name to be removed: ");
String name= keyboard.next().toLowerCase();// entry name to be removed
Iterator<BestFriends> nameIter = myBFFs.iterator(); //manipulate ArrayList
while (nameIter.hasNext()){
best = nameIter.next(); // obtained object list
if (best.getNickName().trim().toLowerCase().equals(name)){ // if equals name
nameIter.remove(best); // remove to arraylist
}
}
}
Update
public void changeABFF()
{
System.out.print("Enter a friend's name to be change: ");
String name= keyboard.next().toLowerCase().trim();//entry name to be update
Iterator<BestFriends> nameIter = myBFFs.iterator();
while (nameIter.hasNext()){
best = nameIter.next();
if (best.getNickName().trim().toLowerCase().equals(name)){// if equals name
best.setNickName("NEW DATE");//update data with new data Setters
....
}
}
}
In your remove method you do not accept any input of the values
public void removeABFF()
{
System.out.print("Enter a friend's name to be removed: ");
int i = 0;
boolean found = false;
while (i < myBFFs.size() && !found)
....
As you are using firstNamer and lastName to find the object you needs these values
System.out.println("Enter a first name: ");
String firstName = keyboard.next();
System.out.println("Enter a last name: ");
String lastName = keyboard.next();

Calling methods from classes error

I'm a beginner at Java so sorry for the mess ups.
Im creating a Library program and have 4 classes: Library, Book, BookInterface and Patron.
I'm in the last couple of stages of the program however I have error messages in the Library class as I'm having trouble with instances.
I got the error message "Cannot make a static reference to the non-static method" in ALL of my switch statements. I tried to create an instance of the Library class in case 1 but still an error message. Also I can't change those methods to static. Any help is much appreciated! :)
Library class:
import java.awt.List;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
import java.util.Collections;
public class Library
{
public static void main(String[] args)
{
//create new library
Library newLibrary = new Library();
}
public Library()
{
Library library = new Library();
Scanner input = new Scanner(System.in);
int choice = 0;
System.out.println("********************Welcome to the Public Library!********************");
System.out.println(" Please Select From The Following Options: ");
System.out.println("**********************************************************************");
while(choice != 9)
{
System.out.println("1: Add new patron");
System.out.println("2: Add new book");
System.out.println("3: Edit patron");
System.out.println("4: Edit book");
System.out.println("5: Display all patrons");
System.out.println("6: Display all books");
System.out.println("7: Check out book");
System.out.println("8: Check in book");
System.out.println("9: Search book");
System.out.println("10: Search Patron");
System.out.println("11: Exit");
choice = input.nextInt();
switch(choice)
{
case 1: //Add new patron
//ERROR: Patron cannot be resolved or is not a field
library.Patron.newPatron();
break;
case 2: //Add new book
//ERROR: Cannot make a static reference to the non-static method
Book.addBook();
break;
case 3: //Edit patron name
Patron.editName();
break;
case 4: //edit book
//ERROR: Cannot make a static reference to the non-static method
Book.editBook();
break;
case 5: //display all patrons
System.out.println(Book.UserList);
break;
case 6: //display all books
//System.out.println(Book.OrigBookList);
Book.libraryInventory();
//Book.bookStatus()
break;
case 7: //check out a book
//ERROR: Cannot make a static reference to the non-static method
Patron.CheckOutBook();
break;
case 8: //check in a book
//ERROR: Cannot make a static reference to the non-static method
Patron.CheckInBook();
break;
case 9: //search book
//ERROR: Cannot make a static reference to the non-static method
Patron.bookStatus();
break;
case 10://search Patron
Patron.searchPatron();
break;
case 11: //exit program
}
}
}
}
Book class:
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class Book implements BookInterface
{
Scanner input = new Scanner(System.in);
static ArrayList <String> UserList = new ArrayList<String>();
static ArrayList <String> BookList = new ArrayList <String> (); //display just titles// use when checking out books
static ArrayList <String> OrigBookList = new ArrayList <String> (); //keep track of all titles ever entered
public String title;
public String author;
public String book;
public boolean checkIn;
private String status;
private String borrower;
public Book(String t, String a)
{
title = t;
author = a;
}
//constructor create new book
public Book(String newTitle)
{
title = newTitle;
}
public String toString()
{
return title + " " + author;
}
public String getTitle()
{
return title;
}
public void setTitle(String title)
{
this.title = title;
}
public String getAuthor()
{
return author;
}
public void setAuthor(String author)
{
this.author = author;
}
public void addBook()
{
Scanner input = new Scanner(System.in);
Scanner inputread = new Scanner(System.in);
System.out.print("Enter book title: ");
String title1 = inputread.nextLine();
Scanner input1 = new Scanner(System.in);
System.out.print("Enter book author: ");
String author1 = inputread.next();
Book fullBook = new Book(title1, author1); //create constructor w/ title & author
Book book1 = new Book(title1); //constructor w/ just title to be used to display all books
//BookList.add(title1);
OrigBookList.add(title1);
setStatus("IN"); //false = checked in
System.out.println("-----------------------------------------------");
System.out.println("-----" + title1 + " is now in the library!-----");
System.out.println("-----------------------------------------------");
}
public void editBook()
{
Scanner inputread = new Scanner(System.in);
System.out.println("Enter original book title: ");
String origTitle = inputread.nextLine();
System.out.println("Enter edited book title: ");
String editedTitle = inputread.nextLine();
Collections.replaceAll(Book.UserList, origTitle, editedTitle);
System.out.println("------------------------------------------------------");
System.out.println(origTitle + " has been changed to " + editedTitle + "!");
System.out.println("------------------------------------------------------");
}
public String getStatus(String book)
{
return status;
}
public void setStatus(String status)
{
this.status = status;
}
public void setBorrower(String borrower)
{
this.borrower = borrower;
}
public String getBorrower(String checkPatron)
{
return borrower;
}
public String getBook(String checkPatron)
{
return book;
}
public void setBook(String bookCheckOut)
{
this.book = bookCheckOut;
}
public void libraryInventory()
{
System.out.println("------------------ Library Inventory: ---------------");
for(int i =0; i<= OrigBookList.size()-1; i++)
{
//Book Title: checked in/out
System.out.println(OrigBookList.get(i) + ":" + getStatus(OrigBookList.get(i)));
}
System.out.println("-----------------------------------------------------");
}
}
Patron class:
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Scanner;
public class Patron
{
Scanner input = new Scanner(System.in);
private String fullName;
int bookCount = 0; //amount books user has in pocket
int books = 0;
//constructor to "add new patron" by entering their name.
public Patron(String newName)
{
fullName = newName;
}
public String toString()
{
return fullName;
}
public String getName()
{
return fullName;
}
public void CheckOutBook()
{
//create and format due date (7days)
GregorianCalendar returnDate = new GregorianCalendar();
returnDate.add(GregorianCalendar.DATE, 7);
Date d = returnDate.getTime();
DateFormat df = DateFormat.getDateInstance();
String dueDate = df.format(d);
Scanner inputread = new Scanner(System.in);
Scanner input = new Scanner(System.in);
System.out.println("Enter full patron name: ");
String borrower = inputread.nextLine();
System.out.println("Enter book title to check out: ");
String bookCheckOut = inputread.nextLine();
Book checkOut = new Book(bookCheckOut);
if(Book.BookList.contains(bookCheckOut))
{
Book.BookList.remove(bookCheckOut);
checkOut.setStatus("OUT");
checkOut.setBorrower(borrower);
Book.BookList.remove(bookCheckOut);
System.out.println("----------" + bookCheckOut + " has been checked out!----------");
System.out.println("-------------------BOOK STATUS:---------------------");
System.out.println("Book Title: " + bookCheckOut);
System.out.println("Book Status: Checked out");
System.out.println("Borrower: " + borrower);
System.out.println("Due Date: " + dueDate);
System.out.println("----------------------------------------------------");
}
else if (!(Book.UserList.contains(borrower)))
{
System.out.println("Patron is not a part of library system. Please enter patron in system.");
}
else if (!(Book.BookList.contains(bookCheckOut)))
{
System.out.println(bookCheckOut + " is not in the library. Please enter "
+ "a different book to be checked out");
}
}
public void CheckInBook()
{
Scanner inputread = new Scanner(System.in);
System.out.println("Enter book title to be checked in: ");
String bookCheckIn = inputread.nextLine();
Book checkOut = new Book(bookCheckIn);
if((!Book.BookList.contains(bookCheckIn)) && Book.OrigBookList.contains(bookCheckIn))
{
Book.BookList.add(bookCheckIn);
checkOut.setStatus("IN");
System.out.println("------------------------------------------------------");
System.out.println("-----" + bookCheckIn + " has been checked in!-----");
System.out.println("------------------------------------------------------");
}
else
System.out.println(bookCheckIn + " is not part of the library system. Please enter "
+ "a different book to be checked in");
}
public boolean canBorrow()
{
if(bookCount <= 3)
{
return true;
}
else
{
return false;
}
}
public static void editName()
{
Scanner inputread = new Scanner(System.in);
System.out.println("Enter original patron full name: ");
String origName = inputread.nextLine();
System.out.println("Enter edited patron full name: ");
String editedName = inputread.nextLine();
Collections.replaceAll(Book.UserList, origName, editedName);
System.out.println("------------------------------------------------------");
System.out.println(origName + " has been changed to " + editedName + "!");
System.out.println("------------------------------------------------------");
}
public void newPatron()
{
Scanner inputread = new Scanner(System.in);
System.out.println("Enter patron full name: ");
String name = inputread.nextLine();
Book.UserList.add(name); //add name to userList
Patron patron1 = new Patron(name);
System.out.println("-----------------------------------------------------------------");
System.out.println("-----" + name + " has been added to the library system" + "-----");
System.out.println("-----------------------------------------------------------------");
}
public void bookStatus() //STOPS
{
Scanner input = new Scanner(System.in);
Scanner inputread = new Scanner(System.in);
System.out.println("Enter book title: ");
String checkStatus = inputread.nextLine();
Book status = new Book(checkStatus);
if(Book.OrigBookList.contains(checkStatus) && status.getStatus(checkStatus) == "OUT")
{
System.out.println("Status: checked out");
System.out.println("Borrower: " + status.getBorrower(checkStatus));
}
else if(Book.OrigBookList.contains(checkStatus) && status.getStatus(checkStatus) == "IN")
{
System.out.println("Status: checked in");
System.out.println("Borrower: none");
}
else if(!(Book.OrigBookList.contains(checkStatus)))
System.out.print("Book is not in library system. Please add the book first.");
}
public void searchPatron() //WORKS!!!
{
Scanner inputread = new Scanner(System.in);
System.out.println("Enter patron full name: ");
String checkPatron = inputread.nextLine();
Book search = new Book(checkPatron);
if(Book.UserList.contains(checkPatron))
{
System.out.println("-------------------------------------------------");
System.out.println("Books checked out: " + search.getBook(checkPatron));
System.out.println("-------------------------------------------------");
}
else
System.out.println("Patron is not part of the library system. Please create new patron first.");
}
}
Since you're calling non static methods of Patron and Book you have to make their objects to call these methods. Only static methods can be called directly on the Class. Check links below for details on static members
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/variables.html
https://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html
Couple of things to keep in mind
Constructors should be used to create objects only your Library() constructor is doing too much work, try to put it outside constructor.
Your case 11 was not exiting from the loop, I have added System.exit(0) there.
Close the Scanner object using input.close()
Try some exception handling in the code to be safe.
In Java it's convention to keep first letter small in naming non static fields and methods. Check this link https://docs.oracle.com/javase/tutorial/java/nutsandbolts/variables.html
Here's the corrected code
import java.awt.List;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
import java.util.Collections;
public class Library {
public static void main(String[] args) {
// create new library
Library newLibrary = new Library();
}
public Library() {
Scanner input = new Scanner(System.in);
int choice = 0;
System.out
.println("********************Welcome to the Public Library!********************");
System.out
.println(" Please Select From The Following Options: ");
System.out
.println("**********************************************************************");
while (choice != 9) {
System.out.println("1: Add new patron");
System.out.println("2: Add new book");
System.out.println("3: Edit patron");
System.out.println("4: Edit book");
System.out.println("5: Display all patrons");
System.out.println("6: Display all books");
System.out.println("7: Check out book");
System.out.println("8: Check in book");
System.out.println("9: Search book");
System.out.println("10: Search Patron");
System.out.println("11: Exit");
choice = input.nextInt();
//creating Patron and Book objects
Patron patron = new Patron();
Book book = new Book();
switch (choice) {
case 1: // Add new patron
// ERROR: Patron cannot be resolved or is not a field
patron.newPatron();
break;
case 2: // Add new book
// ERROR: Cannot make a static reference to the non-static
// method
book.addBook();
break;
case 3: // Edit patron name
patron.editName();
break;
case 4: // edit book
// ERROR: Cannot make a static reference to the non-static
// method
book.editBook();
break;
case 5: // display all patrons
System.out.println(Book.UserList);
break;
case 6: // display all books
// System.out.println(Book.OrigBookList);
Book.libraryInventory();
// Book.bookStatus()
break;
case 7: // check out a book
// ERROR: Cannot make a static reference to the non-static
// method
patron.CheckOutBook();
break;
case 8: // check in a book
// ERROR: Cannot make a static reference to the non-static
// method
patron.CheckInBook();
break;
case 9: // search book
// ERROR: Cannot make a static reference to the non-static
// method
patron.bookStatus();
break;
case 10:// search Patron
patron.searchPatron();
break;
case 11: // exit program
//added exit(0)
System.exit(0);
}
}
}
}

How to remove objects from ArrayLists

So i have this homework, to create a java movie program. It should have the add movie (title, actor and date of appearance), show (all the movies added) and remove movie(by movie title) options.
Up till now i was able to create the addMovie(), and showMovie() methods...but i got really stuck ad removeMovies().
Here is the code for the Main.java:
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
static Scanner input = new Scanner(System.in);
static ArrayList<Movies> movHolder = new ArrayList<Movies>();
public static void main(String[] args) {
int op = -1;
while (op != 0){
op= menuOption();
switch(op){
case 1:
addMovies();
break;
case 2:
removeMovies();
break;
case 3:
showMovies();
break;
case 0:
System.out.print("\n\nYou have exited the program!");
break;
default:
System.out.println("\nWrong input!");
}
}
}
public static int menuOption(){
int option;
System.out.println("\nMenu\n");
System.out.println("1. Add new movies");
System.out.println("2. Remove movies");
System.out.println("3. Show all movies");
System.out.println("0. Exit program");
System.out.print("\nChoose an option: ");
option = input.nextInt();
return option;
}
public static void addMovies(){
String t, a, d;
input.nextLine();
System.out.println("\n---Adding movies---\n");
System.out.print("Enter title of movie: ");
t = input.nextLine();
System.out.print("Enter actor's name: ");
a = input.nextLine();
System.out.print("Enter date of apearance: ");
d = input.nextLine();
Movies mov = new Movies(t, a, d);
movHolder.add(mov);
}
public static void removeMovies(){
int choice;
System.out.println("\n---Removing movies by title---\n");
for(int i = 0; i < movHolder.size(); i++){
System.out.println((i+1)+ ".) "+ movHolder.get(i).toString());
}
System.out.print("Enter movie do you want to remove?");
choice = input.nextInt();
}
public static void showMovies(){
System.out.print("---Showing movie list---\n");
for(int i = 0; i < movHolder.size(); i++){
System.out.println((i+1)+ ".) "+ movHolder.get(i).toString());
}
}
}
And here is the Movies.java with the Movie class:
public class Movies {
private String title;
private String actor;
private String date;
public Movies (String t, String a, String d){
title = t;
actor = a;
date = d;
}
public Movies(){
title = "";
actor = "";
date = "";
}
public String getTitle(){
return title;
}
public String getActor(){
return actor;
}
public String getDate(){
return date;
}
public String toString(){
return "\nTitle: " + title +
"\nActor: " + actor +
"\nRelease date: " + date;
}
}
As you could probably see, i am a very beginner java programmer.
Please, if there is anyway someone could help with the removeMovie() method, i would be very grateful.
Since you have the index of the movie that should be removed (choice - 1) you can use ArrayList.remove(int)
System.out.print("Enter movie do you want to remove?");
choice = input.nextInt();
movHolder.remove(choice-1);
You can use the remove(int index) method:
public static void removeMovies(){
int choice;
System.out.println("\n---Removing movies by title---\n");
for(int i = 0; i < movHolder.size(); i++){
System.out.println((i+1)+ ".) "+ movHolder.get(i).toString());
}
System.out.print("Enter movie do you want to remove?");
choice = input.nextInt();
// Decrement the index because you're asking the user for a 1 based input.
movHolder.remove(choice - 1)
}
}

"p" cannot be resolved to a variable

I have to use a switch statement to allow a user to select what they want to do, if they select "1", it will allow them to add a person to a database. In the switch statement for "1", i am getting a syntax error stating that "p" cannot be resolved to a variable. However, I have tried everything i can possibly think of to get this to work and it will not. any idea?
package hartman;
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Printer.printWelcome();
Scanner keyboard = new Scanner(System.in);
ArrayList<Person> personList = new ArrayList<>();
boolean keepRunning = true;
while (keepRunning) {
Printer.printMenu();
Printer.printPrompt("Please enter your operation: ");
String userSelection = keyboard.nextLine();
switch (userSelection) {
case "1":
Database.addPerson(p);
break;
case "2":
Database.printDatabase(personList);
break;
case "3":
Printer.printSearchPersonTitle();
String searchFor = keyboard.nextLine();
Database.findPerson(searchFor);
break;
case "4":
keepRunning = false;
break;
default:
break;
}
}
Printer.printGoodBye();
keyboard.close();
}
}
This is Database.java -
package hartman;
import java.util.ArrayList;
import java.util.Scanner;
public class Database {
static Scanner keyboard = new Scanner(System.in);
private static ArrayList<Person> personList;
public Database() {
}
public static void addPerson(Person personList2) {
Printer.printAddPersonTitle();
Printer.printPrompt(" Enter first name: ");
String addFirstName = keyboard.nextLine();
Printer.printPrompt(" Enter last Name: ");
String addLastName = keyboard.nextLine();
Printer.printPrompt(" Enter social Security Number: ");
String addSocial = keyboard.nextLine();
Printer.printPrompt(" Enter year of birth: ");
int addYearBorn = Integer.parseInt(keyboard.nextLine());
System.out.printf("\n%s, %s saved!\n", addFirstName, addLastName);
Person person = new Person();
person.setFirstName(addFirstName);
person.setLastName(addLastName);
person.setSocialSecurityNumber(addSocial);
person.setYearBorn(addYearBorn);
personList.add(personList2);
}
public static void printDatabase(ArrayList<Person> personList) {
System.out
.printf("\nLast Name First Name Social Security Number Age\n");
System.out
.printf("=================== =================== ====================== ===\n");
for (Person p : personList) {
System.out.printf("%-20s%-21s%-24s%s\n", p.getLastName(),
p.getLastName(), p.getSocialSecurityNumber(), p.getAge());
}
}
public static ArrayList<Person> findPerson(String searchFor) {
ArrayList<Person> matches = new ArrayList<>();
for (Person p : personList) {
boolean isAMatch = false;
if (p.getFirstName().equalsIgnoreCase(searchFor)) {
isAMatch = true;
}
if (p.getLastName().equalsIgnoreCase(searchFor)) {
isAMatch = true;
}
if (p.getSocialSecurityNumber().contains(searchFor)) {
isAMatch = true;
;
}
if (String.format("%d", p.getAge()).equals(searchFor))
if (isAMatch) {
}
matches.add(p);
}
return matches;
}
}
The compiler cant resolve p to a variable, because you declare p nowhere.
Better solution:
I think its much nicer to do the person creation process directly in the database, so do the following:
Change Database.java to this:
public static void addPerson() {
Printer.printAddPersonTitle();
Printer.printPrompt(" Enter first name: ");
String addFirstName = keyboard.nextLine();
Printer.printPrompt(" Enter last Name: ");
String addLastName = keyboard.nextLine();
Printer.printPrompt(" Enter social Security Number: ");
String addSocial = keyboard.nextLine();
Printer.printPrompt(" Enter year of birth: ");
int addYearBorn = Integer.parseInt(keyboard.nextLine());
System.out.printf("\n%s, %s saved!\n", addFirstName, addLastName);
Person person = new Person();
person.setFirstName(addFirstName);
person.setLastName(addLastName);
person.setSocialSecurityNumber(addSocial);
person.setYearBorn(addYearBorn);
personList.add(person);
}
Change first code to:
Database.addPerson();

Categories