Displaying a multiple object arraylist? - java

I am curious as to how would I show a multiple object arraylist in Java. The array list contains both string and int.
This is the class of which I am making a arraylist of.
public class Movie
{
public int rating;
public String title, directorName, actorOne, actorTwo, actorThree;
public Movie(String Title, String Director, String ActorOne, String ActorTwo, String ActorThree, int Rating)
{
title = Title;
directorName = Director;
actorOne = ActorOne;
actorTwo = ActorTwo;
actorThree = ActorThree;
rating = Rating;
}
public void setTitle(String Title)
{
title = Title;
}
public String getTitle()
{
return title;
}
public void setDirector(String Director)
{
directorName = Director;
}
public String getDirector()
{
return directorName;
}
public void setActorOne(String ActorOne)
{
actorOne = ActorOne;
}
public String getActorOne()
{
return actorOne;
}
public void setActorTw0(String ActorTwo)
{
actorTwo = ActorTwo;
}
public String getActorTwo()
{
return actorTwo;
}
public void setActorThree(String ActorThree)
{
actorThree = ActorThree;
}
public String getActorThree()
{
return actorThree;
}
}
This is my main class
import java.io.*;
import java.util.*;
public class Database
{
Scanner input = new Scanner(System.in);
boolean start;
ArrayList<Movie> movie = new ArrayList<Movie>();
String title, director, actOne, actTwo, actThree;
int rating;
public Database()
{
// initialise instance variables
this.display();
}
public void display()
{
while (start = true)
{
System.out.println("Welcome to the Movie Database");
System.out.println
(
"Select an option \n" +
"1 Find Movie \n" +
"2 Add Movie \n" +
"3 Delete Movie \n" +
"4 Display Favourtite Movies \n" +
"5 Exit Database \n"
);
int choice = input.nextInt();
input.nextLine();
switch(choice)
{
case 1:
break;
case 2:
this.addMovie();
break;
case 3:
break;
case 4:
break;
case 5:
this.exit();
break;
default:
System.out.println("Invalid selection.");
break;
}
}
}
public void exit()
{
System.out.println("Exiting");
start = false;
System.exit(0);
}
public void addMovie()
{
System.out.println("Insert Movie Name: ");
title = input.nextLine();
System.out.println("Insert Director Name: ");
director = input.nextLine();
System.out.println("Insert Actor One Name: ");
actOne = input.nextLine();
System.out.println("Insert Actor Two Name: ");
actTwo = input.nextLine();
System.out.println("Insert Actor Three Name: ");
actThree = input.nextLine();
System.out.println("Insert Movie Rating: ");
rating = input.nextInt();
movie.add(new Movie(title, director, actOne, actTwo, actThree, rating));
}
}
I just wish to see if I my program is actually adding to array list.
Thank you

You may find helpful overriding toString method in the movie class and then printing the arrayList everytime you do something with it...
System.out.println("actual state of the list: "+movie);
and override the toString method in the movie class... somthing descripting the object... like:
#Override
public String toString() {
return "Movie [rating=" + rating + ", title=" + title + ", directorName=" + directorName + ", actorOne="
+ actorOne + ", actorTwo=" + actorTwo + ", actorThree=" + actorThree + "]";
}

Related

Exception in thread "main" java.lang.NullPointerException when trying to run code in compiler [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed last year.
Running into trouble with the output of my code (listed below, separate files and all) where I can execute the correct action up until I need to execute one directly after another. It's spitting out the Exception in thread "main" java.lang.NullPointerException error along with at which lines it is incorrect, however I don't know how to fix it as of now. (This is done in Eclipse compiler)
public class Assignment4
{
public static void main (String[] args)
{
// local variables, can be accessed anywhere from the main method
char input1 = 'Z';
//String inputInfo= "";
String name, firstName, lastName, city ;
int years = 0;
String line = new String();
// instantiate a Team object
Team suns = null;
printMenu();
//Create a Scanner object to read user input
Scanner scan = new Scanner(System.in);
do // will ask for user input
{
System.out.println("What action would you like to perform?");
line = scan.nextLine();
if (line.length() == 1)
{
input1 = line.charAt(0);
input1 = Character.toUpperCase(input1);
// matches one of the case statement
switch (input1)
{
case 'A': //Add a coach
System.out.print("Please enter the Coach's information:\n");
System.out.print("Enter coach's first name:\t");
firstName = scan.nextLine();
System.out.print("Enter coach's last name:\t");
lastName = scan.nextLine();
System.out.print("Enter coach's years of experience:\t");
years = scan.nextInt();
scan.nextLine();
Coach sunsCoach = new Coach(firstName, lastName, years);
System.out.print("\nPlease enter the Team's information:");
System.out.print("\nEnter teams name:\t");
name = scan.nextLine();
System.out.print("Enter Team's city:\t");
city = scan.nextLine();
suns = new Team(name, sunsCoach, city);
break;
case 'D': //Display course
System.out.print(suns.toString());
break;
case 'Q': //Quit
break;
case '?': //Display Menu
printMenu();
break;
default:
System.out.print("Unknown action\n");
break;
}
}
else
{
System.out.print("Unknown action\n");
}
} while (input1 != 'Q' || line.length() != 1);
scan.close();
}
/** The method printMenu displays the menu to a user **/
public static void printMenu()
{
System.out.print("Choice\t\tAction\n" +
"------\t\t------\n" +
"A\t\tAdd Coach\n" +
"D\t\tDisplay Team\n" +
"Q\t\tQuit\n" +
"?\t\tDisplay Help\n\n");
}
}
Along with this code, there are my two child class files, Coach.java and Team.java respectively, listed below.
public class Coach
{ String firstName, lastName; //constructor
int years;
{ String numYears;
firstName = lastName = numYears = "?";
}
public Coach(String first, String last, int years) { //Set variables
firstName = first;
lastName = last;
int numYears = years;
}
//Accessors
public String getFirstName()
{return firstName;}
public String getLastName()
{return lastName;}
public String getYears()
{String numYears = null;
return numYears;}
// Mutators
public void setFirstName(String theFirstName)
{firstName = theFirstName;}
public void setLastName(String theLastName)
{lastName = theLastName;}
public void setYears(int years)
{int numYears = years;}
public String toString() {
String output = "\nLast Name:\t" + lastName + "\nFirst Name:\t " + firstName;
output += "\nYears of Experience:\t " + getYears() + "\n";
return output;
}
}
public class Team {
String teamName;
Coach coach;
String getCity;
//Constructor
public Team() {
teamName = getCity = "?";
}
public Team(String name, Coach coach, String cityName)
{ teamName = name;
}
//Accessors
public String getName() {return teamName;}
public Coach getCoach() {return coach;}
public String getCity() {return getCity;}
//Mutators
public void setName(String theName) {teamName = theName;}
public void setCity(String someCity) {getCity = someCity;}
public void setCoach(String firstName, String lastName, int years)
{ coach = new Coach (firstName, lastName, years);
}
public String toString()
{ String output = "Team's name:\t" + teamName + " at " + getCity() + "\nCoach Information:";
output += coach.toString();
return output;
}
}
Running the code, and putting in inputs until I wish to select option D, will eventually yield this specific error:
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "Coach.toString()" because "this.coach" is null
at Team.toString(Team.java:30)
at Assignment4.main(Assignment4.java:68)
suns = new Team(name, sunsCoach, city);
As I can see you are passing sunsCoach as a parameter to the constructor of Team, but you are not initialising the coach object.
Update your code from
public Team(String name, Coach coach, String cityName)
{
teamName = name;
}
to
public Team(String name, Coach coach, String cityName)
{
teamName = name;
coach = coach;
getCity = cityName;
}
this would resolve the NullPointerException

How can I solve with Java's map containsKey() method?

I checked the code and saving data to the HashMap is correct, when typing ADD. Then after choosing option FIND I can get to the dedicated function but the method is unable to show me found object even if it is correct 100%.
Please check this code out and tell me why it does not find right objects in "public void showInfo(String name, String secondName)" for class Company that is sparked by TYPING "FIND" in class CompanyApp
import java.util.InputMismatchException;
import java.util.Objects;
import java.util.Scanner;
public class CompanyApp {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
options[] values = options.values();
int choose;
int EXIT_NR = 2;
Company ref = new Company();
do {
System.out.println("Available options: ");
for (options one : values) {
System.out.println(one.getDescription() + " - " + one.name());
}
System.out.println("Choose one: ");
try {
choose = options.valueOf(in.nextLine()).ordinal();
if (Objects.equals(EXIT_NR, choose)) break;
if (choose < 0 || choose >= options.values().length) {
throw new IllegalArgumentException("Choose 0, 1 or 2!");
}
options(choose);
} catch (InputMismatchException e) {
System.out.println("Choose a number ");
}
} while (1 == 1);
}
static void options(int choose){
Company ref = new Company();
Scanner info = new Scanner(System.in);
switch (choose){
case 0:
System.out.println("Type in the name of the worker: ");
String name = info.nextLine();
System.out.println("Type in the second name of the worker: ");
String secondName = info.nextLine();
System.out.println("Type in the salary: ");
double salary = info.nextDouble();
info.nextLine();
ref.add(new Employee(name, secondName, salary));
break;
case 1:
System.out.println("Type in the name of the worker you want to find: ");
String name2 = info.nextLine();
System.out.println("Type in the second name of the worker you want to
find: ");
String secondName2 = info.nextLine();
ref.showInfo(name2, secondName2);
break;
}
}
}
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
public class Company {
private Map<String, Employee> map = new HashMap<>();
public void add(Employee employee){
String key = employee.getName() + " " + employee.getSecondName();
if(!map.containsKey(key)){
map.put(key, employee);
System.out.println("Added object to map");}
}
public void showInfo(String name, String secondName){
String key = name + " " + secondName;
System.out.println("in showinfo method");
if(map.containsKey(key)){
System.out.println("found an object");
Employee employee = map.get(key);
System.out.println(employee.getName());
}}}
enum options {
ADD("Add employee "), FIND("Find employee"), EXIT("Exit program");
private String description;
options(String description) {
this.description = description;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
#Override
public String toString() {
return "options{" +
"description='" + description + '\'' +
'}';
}
}
String name;
String secondName;
double salary;
public Employee(String name, String secondName, double salary) {
this.name = name;
this.secondName = secondName;
this.salary = salary;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSecondName() {
return secondName;
}
public void setSecondName(String secondName) {
this.secondName = secondName;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
#Override
public String toString() {
return "Employee{" +
"name='" + name + '\'' +
", secondName='" + secondName + '\'' +
", salary=" + salary +
'}';
}
}
The problem is in the method static void options(int choose). You need to pass the Company-Object and use it there like this:
Call from main method (ref is the Company-Object you create in the main method)
options(choose, ref);
The options-method with the Company as second parameter:
static void options(int choose, Company ref){
Scanner info = new Scanner(System.in);
switch (choose){
case 0:
System.out.println("Type in the name of the worker: ");
String name = info.nextLine();
System.out.println("Type in the second name of the worker: ");
String secondName = info.nextLine();
System.out.println("Type in the salary: ");
double salary = info.nextDouble();
info.nextLine();
//use the passed Company here
ref.add(new Employee(name, secondName, salary));
break;
case 1:
System.out.println("Type in the name of the worker you want to find: ");
String name2 = info.nextLine();
System.out.println("Type in the second name of the worker you want to find: ");
String secondName2 = info.nextLine();
//and here
ref.showInfo(name2, secondName2);
break;
}
}
Explanation what is happening in your code
As mentioned, the problem is in the method static void options(int choose).
Here you create a new Company-Object which is not passed in any way to the main method.
This is what happens, when you use ADD and a FIND afterwards:
Call options from main method with ADD
new Company-Object is created in options
new Employee-Object is added to the Company from the previous point
the method ends -> the created Company-Object is "thrown away" (eligible for Garbage Collection)
Call options from main method with FIND
new Company-Object is created in options(therefore no Employees in it)
no Employee can be found, because there is no entry in the map of the newly created Company
The map is empty at the time when you're trying to get the data from it using FIND option. The reason for that is you recreate the Company object in the options method:
Company ref = new Company();
At the same time also the map is recreated so there are no records inside.
Also, the Company object in the main method is not used.

Error of "variable might not initialized" while trying to use a class object as a parameter of a method, tried to use a IF to avoid the problem (JAVA)

I'm learning JAVA and I was making the code for a product sales system in a store as an example. So I created the Product, Customer and Sale classes.
In my menu I check if there is a registered product or customer, if yes I call my sales method that has both parameters. However, NetBeans notifies an error that the variable has not been initialized even with the logic not to start the sale if the registration has not been done before.
My basic code:
"variable product might not have been initialized"
"variable customer might not have been initialized"
//Main
//Reg a client and a product, then perform a sale.
package store;
import java.util.Random;
import java.util.Scanner;
public class Store {
static boolean flagProduct=false, flagCustomer=false;
public static void main(String[] args) {
menu();
}
public static void menu() {
System.out.println("\n Choose option:\n"
+ "1 - Product Registration\n"
+ "2 - Customer Registration\n"
+ "3 - Sell\n"
+ "4 - End\n"
);
Scanner scanner = new Scanner(System.in);
int select = scanner.nextInt();
switch (select) {
case 1:
Product product = RegistProduct();
System.out.print("\n Cod product : " + product.getCodProduct());
System.out.print("\n Price product : " + product.getPriceProduct());
System.out.print("\n Quantity product : " + product.getQuantProduct());
menu();break;
case 2:
Customer customer = RegistCustomer();
System.out.print("\n Cod Customer : " + customer.getCodCustomer());
System.out.print("\n Customer name: " + customer.getName());
menu();break;
case 3:
if(flagProduct == true && flagCustomer==true){
Sale sale = sell(product, customer); // *****where the error happens*****
System.out.print("\n Sale code : " + sale.getCodSale());
System.out.print("\n Customer name: " + customer.getName());
System.out.print("\n Cod product : " + product.getCodProduct()+ " -- Quantity:" + sale.getQuantSale()+ " -- Total:" + sale.getValueSale());
} else if(flagProduct == true && flagCustomer==false){
System.out.println("First register the customer ");
menu();break;
} else if(flagProduct == false && flagCustomer==true){
System.out.println("First register the product");
menu();break;
} else
System.out.println("First register the customer and product");
menu();break;
case 4:
break;
default:
System.out.println("Error");
menu();
}
}
public static Product RegistProduct(){
Product product = new Product();
java.util.Scanner scanner = new Scanner(System.in);
System.out.print("Product code:\n");
product.setCodProduct(scanner.nextInt());
System.out.print("Product price:\n");
product.setPriceProduct(scanner.nextFloat());
System.out.print("Product quantity:\n");
product.setQuantProduct(scanner.nextInt());
flagProduct = true;
return product;
}
public static Customer RegistCustomer(){
Customer customer = new Customer();
java.util.Scanner scanner = new Scanner(System.in);
System.out.print("Customer name:\n");
customer.setName(scanner.nextLine());
System.out.print("Customer code:\n");
customer.setCodCustomer(scanner.nextInt());
flagCustomer=true;
return customer;
}
public static Sale Sell(Product product, Customer customer){
java.util.Scanner scanner = new Scanner(System.in);
Random num = new Random();
int codSale = num.nextInt(9999);
Sale sale = new Sale();
sale.setCodSale(codSale);
System.out.print("Customer code:");
int codSaleCustomer = scanner.nextInt();
while (codSaleCustomer != customer.getCodCustomer()){
System.out.print("Non-existent code. Please enter a valid code:\n");
codSaleCustomer = scanner.nextInt();
}
System.out.print("Product code:");
int codSaleProduct = scanner.nextInt();
while (codSaleProduct != product.getCodProduct()){
System.out.print("Non-existent code. Please enter a valid code:\n");
codSaleProduct = scanner.nextInt();
}
System.out.print("Quantity of products purchased:\n");
sale.setQuantSale(scanner.nextInt());
sale.setValueSale(sale.getQuantSale()*product.getPriceProduct());
product.setQuantProduct(product.getQuantProduct() - sale.getQuantSale());
System.out.print("Remaining quantity in stock: "+ product.getQuantProduct());
return sale;
}
}
//Class Product
package store;
public class Product {
private int codProduct;
private float priceProduct;
private int quantProduct;
public int getCodProduct() {
return codProduct;
}
public void setCodProduct(int codProduct) {
this.codProduct = codProduct;
}
public float getPriceProduct() {
return priceProduct;
}
public void setPriceProduct(float priceProduct) {
this.priceProduct = priceProduct;
}
public int getQuantProduct() {
return quantProduct;
}
public void setQuantProduct(int quantProduct) {
this.quantProduct = quantProduct;
}
}
//Class customer
package store;
public class Customer {
private int codCustomer;
private String name;
public int getCodCustomer() {
return codCustomer;
}
public void setCodCustomer(int codCustomer) {
this.codCustomer = codCustomer;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
//Class sale
package store;
public class Sale extends Product{ //I dnno if extends is necessary
private int codSale;
private int quantSale;
private float valueSale;
public int getCodSale() {
return codSale;
}
public void setCodSale(int codSale) {
this.codSale = codSale;
}
public int getQuantSale() {
return quantSale;
}
public void setQuantSale(int quantSale) {
this.quantSale = quantSale;
}
public float getValueSale() {
return valueSale;
}
public void setValueSale(float valueSale) {
this.valueSale = valueSale;
}
}

Method wont increment an int variable inside an object ArrayList?

I've been having this issue with a 'Loanbook' method, the function of it is to increment the 'numOnLoan' variable stored in an object ArrayList by 1, however when i run the method it doesn't seem to change the value.
//Allows loaning of books
public static void Loanbook(Scanner sc, ArrayList<Book> books){
System.out.println("Please enter a book title");
if(sc.hasNext()){
String criteria = sc.nextLine();
for (int i = 0; i < books.size(); i++){
if(criteria.equals(books.get(i).getBookTitle())){
System.out.println("The book " + books.get(i).getBookTitle() + " there are " + books.get(i).getNumInStock() + " in stock");
books.get(i).setNumOnLoan(books.get(i).GetNumOnLoan()+1);
System.out.println("number on loan: " + books.get(i).GetNumOnLoan()); break;
}
} System.out.println("Book Loaned");
LibraryTester.MenuReturn(sc, books);
}
LibraryTester.MenuReturn(sc, books);
}
i suspect this is an issue with the logic of the code by however i edit it, the code doesn't seem to do what i want.
Edit:
book.java
public class Book {
private int id;
private String bookTitle;
private String authorName;
private int bookReleaseYear;
private int numOnLoan;
private int numInStock;
//constructor
public Book(int id, String bookTitle, String authorName, int bookReleaseYear, int numOnLoan, int numInStock) {
this.id = id;
this.bookTitle = bookTitle;
this.authorName = authorName;
this.bookReleaseYear = bookReleaseYear;
this.numOnLoan = numOnLoan;
this.numInStock = numInStock;
}
//Getters/Setters
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getBookTitle() {
return bookTitle;
}
public void setBookTitle(String bookTitle) {
this.bookTitle= bookTitle;
}
public String getAuthorName() {
return authorName;
}
public void setAuthorName(String authorName) {
this.authorName = authorName;
}
public int GetNumOnLoan() {
return numOnLoan;
}
public void setNumOnLoan(int numOnLoan) {
this.numOnLoan = numOnLoan;
}
public int getNumInStock() {
return numInStock;
}
public void setNumInStock(int numInStock) {
this.numInStock = numInStock;
}
public int getBookReleaseYear() {
return bookReleaseYear;
}
public void setBookReleaseYear(int bookReleaseYear) {
this.bookReleaseYear = bookReleaseYear;
}
Library.java
import java.util.ArrayList;
import java.util.Scanner;
public class Library {
public ArrayList<Book> books = new ArrayList<Book>();
public Library(){
super();
}
//Getters/Setters
public Library(ArrayList<Book> books) {
this.books = books;
}
public ArrayList<Book> getBooks() {
return books;
}
public void setBooks(ArrayList<Book> books) {
this.books = books;
}
//Methods
//Allows loaning of books
public static void Loanbook(Scanner sc, ArrayList<Book> books){
System.out.println("Please enter a book title");
if(sc.hasNext()){
String criteria = sc.nextLine();
for (int i = 0; i < books.size(); i++){
if(criteria.equals(books.get(i).getBookTitle())){
System.out.println("The book " + books.get(i).getBookTitle() + " there are " + books.get(i).getNumInStock() + " in stock");
books.get(i).setNumOnLoan(+1);
System.out.println("number on loan: " + books.get(i).GetNumOnLoan()); break;
}
} System.out.println("Book Loaned");
LibraryTester.MenuReturn(sc, books);
}
LibraryTester.MenuReturn(sc, books);
}
}
public static void Returnbook(Scanner sc, ArrayList<Book> books){
System.out.println("Please enter a book title");
if(sc.hasNext()){
String criteria = sc.nextLine();
for (int i = 0; i < books.size(); i++){
if(criteria.equals(books.get(i).getBookTitle())){
System.out.println("The book " + books.get(i).getBookTitle() +
" is in stock," + " there are " + books.get(i).getNumInStock() + " in stock and " + books.get(i).GetNumOnLoan() + " out on loan");
books.get(i).setNumOnLoan(-1);; break;
}
} System.out.println("Book returned");
LibraryTester.MenuReturn(sc, books);
}
}
LibraryTester.java
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Scanner;
public class LibraryTester {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Library lib = new Library();
ArrayList<Book> books = lib.getBooks();
books = Library.CreateBooksArrayList();
MenuInput(sc, books);
sc.close();
lib.setBooks(books);
}
//prints menu
public static void PrintMenu(){
System.out.println("Public Library Menu System");
System.out.println("---------------------------");
System.out.println("1: Add Book");
System.out.println("2: Search for book");
System.out.println("3: Loan Book");
System.out.println("4: Return Book");
System.out.println("5: Amend Book Details");
System.out.println("6: Display all Books");
System.out.println("7: Delete a Book");
System.out.println("8: Other Options");
System.out.println("9: Exit system");
System.out.println("----------------------------");
}
// Allows menu input
public static void MenuInput(Scanner sc, ArrayList<Book> books){
int input = 0;
PrintMenu();
if(sc.hasNextInt()){
input = sc.nextInt();
switch(input){
case 1:Library.AddBook(sc, books);
case 2:Library.SearchBooks(sc, books);;
case 3:Library.Loanbook(sc,books);
case 4:Library.Returnbook(sc, books);
case 5:Library.AmendDetails(sc,books);
case 6:Library.DisplayAllBooks(sc,books);
case 7:Library.Removebook(sc, books);;
case 8:OtherMenu(sc,books);
case 9:System.exit(0);
}
} else {
System.out.println("Please enter a number");
}
}
//Returns user to main menu
public static void MenuReturn(Scanner sc, ArrayList<Book> books){
System.out.println("Press any key to return to the main menu");
if(sc.hasNextLine()){
sc.nextLine();
MenuInput(sc, books);
}
}
}
EDIT: I seem to get the output:
Please enter a book title
Input: book1
Please enter a book title
The book book1 is in stock, there are 5 in stock and 1 out on loan
Book returned
Press any key to return to the main menu
Final Edit: Fixed the issue, the code was not running due to an issue with the if statement, when i removed it there was a problem with all the text appearing at once, which was fixed with am extra 'sc.nextLine'. The issue with the ReturnBook running without call was due to lack of a 'break;' in the menu system.
Thanks everybody for your help, especially Shreyans Sheth
I just dug deep into your code. It seems you had a nasty bug (If it is one). I'll be addressing this specific line in your question: "the function of it is to increment the 'numOnLoan' variable stored in an object ArrayList by 1, however when i run the method it doesn't seem to change the value."
Original method:
public void setNumOnLoan(int numOnLoan)
{
this.numOnLoan= numOnLoan;
}
Method call in Loanbook:
books.get(i).setNumOnLoan(1);
In the LoanBook method, you are simply passing '+1' as a parameter and everytime, only 1 is being assigned. Here's what you need to do.
public void setNumOnLoan(int numOnLoan)
{
//When numOnLoan is 1, as you have passed everytime
//the current value gets incremented by one. I think that is what you wanted.
this.numOnLoan += numOnLoan; //You add it to the existing variable
}
You really should have named that function something else. I'm pretty sure there are more bugs out there but does THIS accomplish what you wanted?
Output:
(First call to Loanbook)
Please enter a book title
input :bbbbb
The book bbbbb there are 5 in stock
number on loan: 2
Book Loaned
(Second call to Loanbook)
Please enter a book title
input: bbbbb
The book bbbbb there are 5 in stock
number on loan: 3
Book Loaned

Finding and removing a name in an ArrayList

Basically i am trying to search for specif names in an Array-list and then remove just that name.I am doing an assignment for college, and it species to search and remove by name, so i cant use the int index of, I am fairly new to java, so ill post my code maybe I am missing something any help would be great.
import java.util.ArrayList;
public class GaaClub {
private ArrayList<Member> players;
{
}
public GaaClub() {
players = new ArrayList<Member>();
}
public void addStanderedMember() {
// create a message object:
StdOut.println("Please enter the members's name: ");
StdIn.readLine();
String name = StdIn.readLine();
StdOut.println("Please enter the members address: ");
String address = StdIn.readLine();
StdOut.println("Please enter the members DOB: ");
String dob = StdIn.readLine();
StdOut.println("Please enter the amount to Pay: ");
double mempaid = StdIn.readDouble();
Member player = new Member(name, address, dob, mempaid);
players.add(player);
}
public void addStandaredPlayer() {
// create a message object:
StdOut.println("Please enter the standard Player's name: ");
StdIn.readLine();
String name = StdIn.readLine();
StdOut.println("Please enter the standard Player's address: ");
String address = StdIn.readLine();
StdOut.println("Please enter the standard Player's DOB: ");
String dob = StdIn.readLine();
StdOut.println("Please enter the amount to Pay: ");
double mempaid = StdIn.readDouble();
StandardPlayer player = new StandardPlayer(name, address, dob, mempaid);
players.add(player);
}
public void addElitePlayer() {
// create a message object:
StdOut.println("Please enter the Elite Players's name: ");
StdIn.readLine();
String name = StdIn.readLine();
StdOut.println("Please enter the Elite Players's address: ");
String address = StdIn.readLine();
StdOut.println("Please enter the Elite Players's DOB: ");
String dob = StdIn.readLine();
StdOut.println("Please enter the the amount to Pay: ");
double mempaid = StdIn.readDouble();
StdOut.println("Please enter the Elite Players's BMI: ");
double bmi = StdIn.readDouble();
StdOut.println("Please enter the Elite Players's height: ");
double height = StdIn.readDouble();
ElitePlayer player = new ElitePlayer(name, address, dob, mempaid, bmi,
height);
players.add(player);
}
public static void main(String[] args) {
GaaClub app = new GaaClub();
app.run();
}
public void memberType() {
StdOut.println("Enter Type of membership: ");
StdOut.println("1) Add a Standard Member");
StdOut.println("2) Add an Elite Player");
StdOut.println("3) Add a Standard Player");
String memberchoice = StdIn.readString();
if (memberchoice.equals("1"))
addStanderedMember();
if (memberchoice.equals("2"))
addElitePlayer();
if (memberchoice.equals("3"))
addStandaredPlayer();
}
public void listNames() {
for (Member player : players) {
player.list();
}
}
public void removeName() {
for (Member player : players) {
listNames();
String sResponse = StdIn.readString();
if (sResponse.equals(player.name))
{
players.remove(player);;
return;
}
}
}
private int mainMenu() {
StdOut.println("1) Add a Member");
StdOut.println("2) Remove Player");
StdOut.println("3) List Names");
StdOut.println("4) List Members");
StdOut.println("0) Exit");
StdOut.print("==>>");
int option = StdIn.readInt();
return option;
}
public void run() {
{
StdOut.println("Posts");
int option = mainMenu();
while (option != 0) {
switch (option) {
case 1:
memberType();
break;
case 2:
removeName();
break;
case 3:
addStanderedMember();
break;
case 4:
listNames();
break;
}
option = mainMenu();
}
StdOut.println("Exiting...");
}
}
}
And Second file:
import java.util.ArrayList;
public class Member {
protected String name;
protected String address;
protected String dob;
protected double mempaid;
public Member(String name, String address, String dob, double mempaid) {
this.name = name;
this.address = address;
this.dob = dob;
this.mempaid = mempaid ;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getDob() {
return dob;
}
public void list(){
System.out.println(name);
}
public void setDob(String dob) {
this.dob = dob;
}
public double getMempaid() {
return mempaid;
}
public void setMempaid(double mempaid) {
this.mempaid = mempaid;
}
#Override
public String toString() {
return "Member [name=" + name + ", address=" + address + ", dob=" + dob
+ ", mempaid=" + mempaid + "]";
}
}
import java.util.ArrayList;
public class StandardPlayer extends Member {
private ArrayList<Competition> competition;
public StandardPlayer(String name, String address, String dob,
double mempaid) {
super(name, address, dob, mempaid);
}
public ArrayList<Competition> getCopmetition() {
return competition;
}
public void setCopmetition(ArrayList<Competition> copmetition) {
this.competition = copmetition;
}
void addCompetiton(Competition c) {
}
void payMembership(double amt) {
mempaid = 0;
}
#Override
public String toString() {
return "StandardPlayer [competition=" + competition + ", name=" + name
+ ", address=" + address + ", dob=" + dob + ", mempaid="
+ mempaid + "]";
}
}
And third file:
import java.util.ArrayList;
public class ElitePlayer extends Member {
private double bmi;
private double height;
private ArrayList<Competition> competition;
public ElitePlayer(String name, String address,
String dob, double mempaid, double bmi, double height) {
super(name, address, dob, mempaid);
this.bmi = bmi;
this.height = height;
}
public double getBmi() {
return bmi;
}
public void setBmi(double bmi) {
this.bmi = bmi;
}
public double getHeight() {
return height;
}
public void setHeight(double height) {
this.height = height;
}
public ArrayList<Competition> getCopmetition() {
return competition;
}
void payMembership(double amt) {
mempaid = 0;
}
#Override
public String toString() {
return "ElitePlayer [bmi=" + bmi + ", height=" + height
+ ", competition=" + competition + ", name=" + name
+ ", address=" + address + ", dob=" + dob + ", mempaid="
+ mempaid + "]";
}
public void setCompetition(ArrayList<Competition> competition) {
this.competition = competition;`enter code here`
}
}
ArrayList has a method which can remove by Object:
ArrayList<String> arr = new ArrayList<String>();
arr.add("Bob");
arr.remove("Bob");
it removes the first instance of the object.
You could of course simulate the same debavior:
ArrayList<String> arr = new ArrayList<String>();
arr.add("Bob");
String searchTerm = "Bob";
for (int i = 0; i < arr.size(); i++) {
if (arr.get(i).equals(searchTerm) {
arr.remove(i);
break;
}
}
This deviation from the built in method would only be recommended if you wanted to have the search delete on some other, or similar condition. For example if it contained the word "Bob"...
ArrayList<String> arr = new ArrayList<String>();
arr.add("Bob Bobingston");
String searchTerm = "Bob";
for (int i = 0; i < arr.size(); i++) {
if (arr.get(i).contains(searchTerm)) {
arr.remove(i);
break;
}
}
It seems as if you already have a loop set-up for it. Just loop through the members, check if the name equals what you're looking for, then remove that member from the list if it is
for(Member mem : players) { //loop through each member in list
if(mem.getName().equalsIgnoreCase("name")) { //check if member's name is "name"
players.remove(mem); //removes member from list if it is
}
}
equalsIgnoreCase(String) checks the string without checking for case sensitivity. It won't care for capitalization. If you care about capitalization, use equals(String)

Categories