Keep a Record of User Input - Java - java

I'm making a event scheduler in Java, and so far I can only add one event. However, I'd like to be able to add more than one event and be able to display them, but the only other option I can think of is using arrays.
I also have a counter called numOfCreatedEvents to keep track of the events and increments when an event is created.
Example of user input
Enter the event ID: A12
Enter the event title: Lorem Ipsum
Enter the fee: $ 10.0
Enter the maximum attendee limit: 15
Enter the start time: 14
Enter the duration time in minutes: 120
Enter requirements (optional): Wear shoes.
Below is my program attempting to use arrays, but when I call the setter methods, they have an error (marked in the code below).
Event.java
Scanner sc = new Scanner(System.in);
// Private instance variables.
private String[] ID;
private String[] title;
private double[] baseFee;
private int[] maxAttendeeLimit;
private int[] startTime;
private int[] durationTime;
private String[] requirements;
private int numOfCreatedEvents;
// Getters.
public String[] getID() {
return this.ID;
}
public String[] getTitle() {
return this.title;
}
public double[] getBaseFee() {
return this.baseFee;
}
public int[] getMaxAttendeeLimit() {
return this.maxAttendeeLimit;
}
public int[] getStartTime() {
return this.startTime;
}
public int[] getDurationTime() {
return this.durationTime;
}
public String[] getRequirements() {
return this.requirements;
}
// Setters.
public void setID(String[] ID) {
this.ID = ID;
}
public void setTitle(String[] title) {
this.title = title;
}
public void setBaseFee(double[] baseFee) {
this.baseFee = baseFee;
}
public void setMaxAttendeeLimit(int[] maxAttendeeLimit) {
this.maxAttendeeLimit = maxAttendeeLimit;
}
public void setStartTime(int[] startTime) {
this.startTime = startTime;
}
public void setDurationTime(int[] durationTime) {
this.durationTime = durationTime;
}
public void setRequirements(String[] requirements) {
this.requirements = requirements;
}
// Schedule a event.
public void scheduleAEvent() {
System.out.println("\n~ SCHEDULE A EVENT ~");
System.out.println("---------------------");
System.out.print("Enter the event ID: ");
String eventID = sc.nextLine();
setID(eventID); // Error here.
System.out.print("Enter the event title: ");
String eventTitle = sc.nextLine();
setTitle(eventTitle); // Error here.
System.out.print("Enter the fee: $");
String baseFee = sc.nextLine();
double eventBaseFee = Double.parseDouble(baseFee);
setBaseFee(eventBaseFee); // Error here.
System.out.print("Enter the maximum attendee limit: ");
String maxAttendeeLimit = sc.nextLine();
int eventMaxAttendeeLimit = Integer.parseInt(maxAttendeeLimit);
setMaxAttendeeLimit(eventMaxAttendeeLimit); // Error here.
System.out.print("Enter the start time: ");
String startTime = sc.nextLine();
int eventStartTime = Integer.parseInt(startTime);
setStartTime(eventStartTime); // Error here.
System.out.print("Enter the duration time in minutes: ");
String durationTime = sc.nextLine();
int eventDurationTime = Integer.parseInt(durationTime);
setDurationTime(eventDurationTime); // Error here.
System.out.print("Enter requirements (optional): ");
String requirements = sc.nextLine();
setRequirements(requirements); // Error here.
// Increase the created event count.
numOfCreatedEvents++;
}
// Print event details.
public void printDetails() {
System.out.println("\n~ EVENTS ~");
System.out.println("-----------");
String pattern = "%-25s %-50s %-25s %-43s %-34s %-34s %-1s\n";
System.out.printf(pattern, "ID", "Title", "Fee", "Maximum Attendee Limit", "Start Time", "Duration Time", "Requirements");
System.out.println("-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------");
// Display the records of events scheduled.
for(int i = 0; i < numOfCreatedEvents; i++) {
System.out.format(pattern, getID(), getTitle(), "$" + getBaseFee(), getMaxAttendeeLimit(), getStartTime(), getDurationTime(), getRequirements());
}
}
Main.java
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String input;
Event event = new Event();
// Main menu.
do {
System.out.println("\n~ EVENT BOOKING SYSTEM ~");
System.out.println("------------------------");
System.out.println("A. Schedule an Event");
System.out.println("B. View Event Details");
System.out.println("X. Exit\n");
System.out.print("Select an option: ");
input = sc.nextLine();
input = input.toUpperCase();
switch(input) {
case "A":
event.scheduleAnEvent();
break;
case "B":
event.printDetails();
break;
case "X":
System.out.println("INFO: You have exited the booking system.");
break;
default:
System.out.println("ERROR: Invalid input!");
}
} while (input.equals("X") == false);
sc.close();
}
Problem: How do I add multiple events and keep a record of them when I call printDetails() to list all of them?
Thank you for your help!

The error is because your setter methods want to take in an array (denoted by the "[]" after the type in the method header), but the places you've marked as an error are attempting to send just a single piece of data of the given type. I think it would be best if you created an Object to represent an event, then had an array that stored these objects. Here's a quick mock-up:
In a file called CalendarEvent.java:
public class CalendarEvent {
private String ID;
private String title;
private double baseFee;
private int maxAttendeeLimit;
private int startTime;
private int durationTime;
private String requirements;
// Getters
public String getID() { return this.ID; }
public String getTitle() { return this.title; }
public double getBaseFee() { return this.baseFee; }
public int getMaxAttendeeLimit() { return this.maxAttendeeLimit; }
public int getStartTime() { return this.startTime; }
public int getDurationTime() { return this.durationTime; }
public String getRequirements() { return this.requirements; }
// Setters
public void setID(String ID) { this.ID = ID; }
public void setTitle(String title) { this.title = title; }
public void setBaseFee(double baseFee) { this.baseFee = baseFee; }
public void setMaxAttendeeLimit(int maxAttendeeLimit) { this.maxAttendeeLimit = maxAttendeeLimit; }
public void setStartTime(int startTime) { this.startTime = startTime; }
public void setDurationTime(int durationTime) { this.durationTime = durationTime; }
public void setRequirements(String requirements) { this.requirements = requirements; }
// this should return a String, built similarly to how you previously did it in your printDetails method
public String toString() {
return ID + " - " + title;
}
// other methods related to modifying a single event go here
// ...
}
In another class called EventHandler.java:
import java.util.Scanner;
public class EventHandler {
CalendarEvent[] myEvents;
public void scheduleAEvent() {
Scanner sc = new Scanner(System.in);
System.out.println("\n~ SCHEDULE A EVENT ~");
System.out.println("---------------------");
CalendarEvent toAdd = new CalendarEvent();
System.out.print("Enter the event ID: ");
toAdd.setID(sc.nextLine());
System.out.print("Enter the event title: ");
toAdd.setTitle(sc.nextLine());
System.out.print("Enter the fee: $");
toAdd.setBaseFee(sc.nextDouble());
System.out.print("Enter the maximum attendee limit: ");
toAdd.setMaxAttendeeLimit(sc.nextInt());
System.out.print("Enter the start time: ");
toAdd.setStartTime(sc.nextInt());
System.out.print("Enter the duration time in minutes: ");
toAdd.setDurationTime(sc.nextInt());
System.out.print("Enter requirements (optional): ");
toAdd.setRequirements(sc.nextLine());
}
// Print event details
public void printDetails() {
System.out.println("\n~ EVENTS ~");
System.out.println("-----------");
String pattern = "%-25s %-50s %-25s %-43s %-34s %-34s %-1s\n";
System.out.printf(pattern, "ID", "Title", "Fee", "Maximum Attendee Limit", "Start Time", "Duration Time", "Requirements");
System.out.println("-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------");
// Display the records of events scheduled.
for(int i = 0; i < myEvents.length; i++) {
System.out.println(myEvents[i]);
}
}
}
I would suggest doing some reading on object oriented design, this is a much more organized way to structure your data. Best of luck, hope this helps.

I am 100% clear what your expectation is. But the looks from your code, you are trying to set a String value to a method that is expecting an array of Strings. i.e. String[]
I suggest to remove the array implementation and replace with List<String>. For example:
private List<String> ID;
public void setID( String i )
{
if( ID == null )
{
ID= new ArrayList<>();
}
ID.add( i );
}
public List<String> getID()
{
return ID;
}
Do this for all the variables. That is ID, Title, baseFee, maxAttendeeLimit, startTime, durationTime, requirements. Because arrays are fixed types and you cannot increment the size of an existing array once created. Access the elements like ID.get(i) within the loop

Here's another example solution.
In the file below, I've removed all of the setters and replaced it with a constructor instead.
Reservation.java
public class Reservation {
private String ID;
private String title;
private double baseFee;
private int maxAttendeeLimit;
private int startTime;
private int durationTime;
private String requirements;
public Reservation(String ID, String title, double baseFee, int maxAttendeeLimit, int startTime, int durationTime, String requirements) {
this.ID = ID;
this.title = title;
this.baseFee = baseFee;
this.maxAttendeeLimit = maxAttendeeLimit;
this.startTime = startTime;
this.durationTime = durationTime;
this.requirements = requirements;
}
public String getID() {
return this.ID;
}
public String getTitle() {
return this.title;
}
public double getBaseFee() {
return this.baseFee;
}
public int getMaxAttendeeLimit() {
return this.maxAttendeeLimit;
}
public int getStartTime() {
return this.startTime;
}
public int getDurationTime() {
return this.durationTime;
}
public String getRequirements() {
return this.requirements;
}
}
Below I've also used an array to store the reservation information.
Main.java
private Reservation[] reservation = new Reservation[5];
private int reservationCounter;
public void printDetails() {
System.out.println("\n~ RESERVATIONS ~");
System.out.println("----------------");
String pattern = "%-25s %-50s %-25s %-43s %-34s %-34s %-1s\n";
System.out.printf(pattern, "ID", "Title", "Fee", "Maximum Attendee Limit", "Start Time", "Duration Time", "Requirements");
System.out.println("-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------");
for(int i = 0; i < reservationCounter; i++)
System.out.format(pattern, reservation[i].getID(), reservation[i].getTitle(), "$" + reservation[i].getBaseFee(), reservation[i].getMaxAttendeeLimit(), reservation[i].getStartTime(), reservation[i].getDurationTime(), reservation[i].getRequirements());
}
Hope this helps!

Related

What is the relationship between two classes they are tied to a Third class?

Getting stuck with my Travail System Project, Confusing a little bit about understanding that if there Classes called Bookable, Hotel and BookingSystem.
Hotel class is implements Bookable. Furthermore, BookingSystem Class is composition from Bookable, So, I need to create method at BookingSystem class which called addHotel.
what I must do about it to make a relationship between Hotel Class and BookingSystem Class.
Thanks In Advance.
Israa
Hotal Class:
public class Hotel implements Bookable {
private String name, location;
private int noOfRooms;
private double roomPrice;
private Date bookingDate;
private ArrayList<Integer> bookedRooms = new ArrayList<Integer>();
private ArrayList<Integer> numberOfrooms = new ArrayList<Integer>();
public Hotel() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public int getNoOfRooms() {
return noOfRooms;
}
public void setNoOfRooms(int noOfRooms) {
this.noOfRooms = noOfRooms;
}
public double getRoomPrice() {
return roomPrice;
}
public void setRoomPrice(double roomPrice) {
this.roomPrice = roomPrice;
}
public Date getBookingDate() {
return bookingDate;
}
public void setBookingDate(Date bookingDate) {
this.bookingDate = bookingDate;
}
public ArrayList<Integer> getBookedRooms() {
return bookedRooms;
}
public void setBookedRooms(ArrayList<Integer> bookedRooms) {
this.bookedRooms = bookedRooms;
}
public String Book() {
if ( numberOfrooms.size() != (bookedRooms.size())) {
for (int i = 0; i < bookedRooms.size(); i++) {
int oldVal = bookedRooms.get(i);
int newVal = oldVal + 1;
bookedRooms.add(bookedRooms.set(i, newVal));
}
}
return null;
}
}
Bookable class:
public interface Bookable {
public String Book();
}
BookingSytsem Class:
public class BookingSystem {
private ArrayList<Customer> customer = new ArrayList<Customer>();
private ArrayList<Bookable> bookable = new ArrayList<Bookable>();
private ArrayList<Operation> operation = new ArrayList<Operation>();
public BookingSystem() {
}
// **
public void addCustomer(String name, int id) {
Customer customers = new Customer(id, name);
customer.add(customers);
System.out.println("new customer " + customers.getName() + " added");
}
// **
public void deleteCustomer(String name, int id) {
Customer customers = new Customer(id, name);
if (customer.contains(name)) {
customer.remove(name);
}
System.out.println("Customer " + customers.getName() + " deleted");
}
public Customer findCustomer(int id) {
for (Customer c : customer) {
if (c.getId() == id) {
return c;
}
}
return null;
}
public void addHotel() {
Hotel H1 = new Hotel();
Scanner name = new Scanner(System.in);
System.out.println("Please Enter the name of Hotel: ");
String n1 = name.nextLine();
bookable.add(H1);
System.out.println("The Hotel " + name + "added");
}
public void makeABooking(Customer c, Bookable b) {
Scanner input =new Scanner(System.in);
System.out.println("Please Enter your name: ");
String name = input.nextLine();
System.out.println("Please Enter your ID: ");
int ID = input.nextInt();
while(true) {
if(ID == -1 && ID == 0) {
System.out.println("Invalid ID. Enter again: ");
name = input.nextLine();
System.out.println("Please Enter your ID: ");
ID = input.nextInt();
}
}
}
}
(Your question is more suitable to https://softwareengineering.stackexchange.com/ - recommend asking it there...)
General speaking it wouldn't make sense to have a Hotel without a name, location or number of rooms so I'd recommend adding a constructor with minimal required information:
public Hotel (String name, String location, int rooms) {
this.name = name;
this.location = location;
this.noOfRooms = rooms;
}
bookingDate makes no sense as a single property of a hotel but rather a property of each booked room so you have a design issue - this is not addressed here.
Again, roomPrice usually varies by room so in a robust solution this would be a property of a room not a hotel - not addressed here.
Why is there a noOfRooms and a numberOfRooms list. In fact, the numberOfRooms list doesn't make sense as a list. I'd just keep the noOfRooms and get rid of numberOfRooms.
An implied property, nbrOfAvailableRooms can be derived from noOfRooms - bookedRooms.size();
I would assume your bookedRooms is a list of room numbers which are booked but that's not possible to tell from your implementation. You should focus on what you want Book to do.
The Book interface method is not documented but it looks like it should simply take an available asset (room) and consider it booked. It should return a boolean success not a String - especially not null.
I recommend writing (in pseudo code) what you want a Book implementation to do - include that in question. That is the core issue you are having.

how to increment the id and take a lengthy description in java

I have made a Note class where i want to increment the id. It is not getting incremented. And also i am taking input description from console . how to accept a lengthy description like("This is Hello World") in java from the user.Please help.
public class Note {
private String title;
private static int id;
private static int count = 0;
private String description;
public static int getId() {
return id = ++count;
}
public String getTitle() {
id++;
return title;
}
public String getDescription(){
return description;
}
public void setDescription(String description){
this.description=description;
}
public String toString() {
return ("Id : " + id + "\n Title :" + title + "\n Description :"+ description);
}
}
Note Console class that accepts input from the user. It accepts 1. Add Note where in i want to accept a proper description from the user. Second View note where with the help of toString method i print the output. Third is EXIT
import java.util.ArrayList;
import java.util.Scanner;
public class NoteConsole {
public static void NoteConsole() {
final int ADD_NOTE = 1;
final int VIEW_NOTE = 2;
final int EXIT = 3;
boolean loop = false;
NoteConsole nc = new NoteConsole();
Note note = new Note();
ArrayList<Note> notes = new ArrayList<Note>();
NoteServiceSerialize service1 = new NoteServiceSerialize();
System.out.println("Write to the Console 1.AddNote, 2. ToView 3. Exit");
Scanner in = new Scanner(System.in);
int choice = in.nextInt();
while (!loop) {
switch (choice) {
case ADD_NOTE: {
System.out.println("Enter the title");
String title = in.next();
note.setTitle(title);
System.out.println("Enter the description");
String description = in.next();
note.setDescription(description);
notes.add(note);
service1.noteSerialize(notes);
break;
}
case VIEW_NOTE: {
for (Note note1 : notes) {
System.out.println(note1);
}
break;
}
case EXIT: {
//code
}
}
}
}
public static void main(String[] args) {
NoteConsole();
}
}
NoteServiceSerialize class -
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
public class NoteServiceSerialize {
public void noteSerialize (ArrayList<Note> list){
try{
FileOutputStream file = new FileOutputStream("D:\\serializable_notes.txt");
ObjectOutputStream obj = new ObjectOutputStream(file);
obj.writeObject(list);
file.close();
obj.close();
}
catch(Exception e){
e.printStackTrace();
}
}
}
Make id instance variable and increase count in constructor of class and assign current value of count to the id
public class Note {
private String title;
private int id;
private static int count = 0;
private String description;
public Note(){
count++;
this.id = count;
}
public int getId() {
return id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription(){
return description;
}
public void setDescription(String description){
this.description=description;
}
public String toString() {
return ("Id : " + id + "\n Title :" + title + "\n Description :"+ description);
}
}
Now every Note object will have separate id.
public class NoteConsole {
//NoteConsole() is not constructor, should avoid same method name and class name
public static void NoteConsole() {
final int ADD_NOTE = 1;
final int VIEW_NOTE = 2;
final int EXIT = 3;
boolean loop = true;
//NoteConsole nc = new NoteConsole();
Note note = new Note();
ArrayList<Note> notes = new ArrayList<Note>();
//NoteServiceSerialize service1 = new NoteServiceSerialize();
Scanner in = new Scanner(System.in);
while (loop) {
System.out.println("Write to the Console 1.AddNote, 2. ToView 3. Exit");
int choice = in.nextInt();
in.nextLine();
switch (choice) {
case ADD_NOTE: {
System.out.println("Enter the title");
//in.nextLine() will read complete line.
String title = in.nextLine();
note.setTitle(title);
System.out.println("Enter the description");
String description = in.nextLine();
note.setDescription(description);
notes.add(note);
//service1.noteSerialize(notes);
break;
}
case VIEW_NOTE: {
for (Note note1 : notes) {
System.out.println(note1);
}
break;
}
case EXIT: {
loop = false;
}
}
}
in.close();
}
public static void main(String[] args) {
NoteConsole();
}
First you should provided the NoteServiceSerialize class too.
for your description problem you should use a in.nextLine() .
and about increment id, doing that in getTitle() is a bad practice.
a better alternative is this way:
private static int lastId;
private int id = nextId();
private static int nextId() {
lastId = ++lastId;
return lastId;
}
and your classes had some other problems too, replace them with this:
public class Note {
private String title;
private String description;
private static int lastId;
private int id = nextId();
private static int nextId() {
lastId = ++lastId;
return lastId;
}
public static int getLastId() {
return lastId;
}
public String getTitle() {
return title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public void setTitle(String description) {
this.description = description;
}
#Override
public String toString() {
return ("Id : " + id + "\nTitle :" + title + "\nDescription :" + description);
}
}
import java.util.ArrayList;
import java.util.Scanner;
public class NoteConsole {
final static ArrayList<Note> notes = new ArrayList<Note>();
public static void NoteConsole() {
NoteServiceSerialize service1 = new NoteServiceSerialize();
NoteConsole nc = new NoteConsole();
Note note = new Note();
final int ADD_NOTE = 1;
final int VIEW_NOTE = 2;
final int EXIT = 3;
boolean loop = false;
Scanner in = new Scanner(System.in);
while (!loop) {
System.out.println("Write to the Console 1.AddNote 2. ToView 3. Exit");
int choice = in.nextInt();
switch (choice) {
case ADD_NOTE:
System.out.println("Enter the title :");
String title = in.next();
System.out.println("Enter the description :");
//if you had a problem with description text remove in.next()
in.next();
String description = in.nextLine();
note.setTitle(title);
note.setDescription(description);
notes.add(note);
service1.noteSerialize(notes);
System.out.println("----------------------");
break;
case VIEW_NOTE:
for (Note note1 : notes) {
System.out.println(note1);
System.out.println("----------------------");
}
break;
case EXIT:
loop = !loop;
break;
default:
System.out.println("Not a Valid Option !!!");
}
System.out.println();
}
}
public static void main(String[] args) {
NoteConsole();
}
}
id would remain 0 (default value of primitive) unless your one of the method is called :
public static int getId() {
return id = ++count;
}
public String getTitle() {
id++;
return title;
}
where you actually increment the value of id. Maybe something like :
public String toString() {
return ("Id : " + getId() + "\n Title :" + title + "\n Description :"+ description);
}
Also make sure your count is initialized as :
private static final int count = 0;

Java Object Array printing null?

I have 3 classes, Movie which is used to add Movie objects to an in MovieDatabase but it keeps printing null.
When I add 2 Movies its like the first Movie is erased and it prints null instead. Also is there a way to check if the position in the array is empty and not print if it is empty?
Here is my Movie class
public class Movie {
private String name;
private String director;
private double fileSize;
private int duration;
private int moviecount;
public Movie()
{
name = null;
director = "";
fileSize = 0;
duration = 0;
}
public void setName(String newName)
{
name = newName;
}
public String getName()
{
return name;
}
public void setDirector(String newDirector)
{
director = newDirector;
}
public String getDirector()
{
return director;
}
public void setfileSize(double newfileSize)
{
fileSize = newfileSize;
}
public double getfileSize()
{
return fileSize;
}
public void setDuration(int newDuration)
{
duration = newDuration;
}
public int getDuration()
{
return duration;
}
and here my MovieDatabase class:
public class MovieDatabase
{
private Movie[] mov;
private int i;
public int count=0;
public MovieDatabase()
{
mov = new Movie[4];
i=0;
}
public void addData(String name, String director, double fileSize, int duration)
{
for(int i=0; i<4; i++)
mov[i] = new Movie();
setData(mov[i],name,director,fileSize,duration);
i++;
count++;
}
private void setData(Movie m,String name, String director, double fileSize, int duration)
{
mov[i].setName(name);
mov[i].setDirector(director);
mov[i].setfileSize(fileSize);
mov[i].setDuration(duration);
}
public void printNames()
{
for (int i = 0; i < mov.length; i++)
{
System.out.println(mov[i].getName());
}
}
}
import java.util.*;
public class Interface {
Scanner console = new Scanner(System.in);
MovieDatabase m = new MovieDatabase();
private void run()
{
int option;
do{
System.out.print("Add Movie(0), Delete Movie(2),Show Movies(3),Movie Count(4) \n");
option = console.nextInt();
switch(option)
{
case 0: addMovie();
break;
case 3: printMovies();
break;
}
}
while(option!=9);
}
public static void main(String[] args){
Interface intFace = new Interface();
intFace.run();
}
public void addMovie()
{
String name, director;
double fileSize;
int duration;
System.out.println("Movie Name: ");
name = console.next();
System.out.println("Movie Director: ");
director = console.next();
System.out.println("Movie File Size: ");
fileSize = console.nextDouble();
System.out.println("Movie Duration: ");
duration = console.nextInt();
System.out.print("Movie Added!");
m.addData(name,director,fileSize,duration);
}
public void printMovies()
{
m.printNames();
}
}
I tried to include only the relevant parts but majority of what I have done so far is relevant.
The problem is in these lines
....
public void addData(String name, String director, double fileSize, int duration)
{
for(int i=0; i<4; i++)
mov[i] = new Movie();
...
Each and every time you're adding a new data, you're erasing all previous records by assigning new movie object to every element in array. This erases all previous data.
You should instead move these 2 lines in MovieDatabase constructor. Or a better option would be to initialize them when you're setting data.
...
public void addData(String name, String director, double fileSize, int duration)
{
setData(mov[i],name,director,fileSize,duration);
i++;
count++;
}
private void setData(Movie m,String name, String director, double fileSize, int duration)
{
mov[i] = new Movie(); //++ edit
mov[i].setName(name);
mov[i].setDirector(director);
mov[i].setfileSize(fileSize);
mov[i].setDuration(duration);
}
...
Also is there a way to check if the position in the array is empty and not print if it is empty?
You can create a method in Movie class which checks whether this movie object is empty or not and returns appropriate result.
public class Movie {
...
...
public boolean isEmpty() {
if(
this.name.isEmpty() &&
this.director &&
this.fileSize == 0 &&
this.duration == 0 &&
this.moviecount == 0
)
return true;
else
return false;
}
...
...
}
Now you can check whether this movie object is empty or not using:
if(mov[i].isEmpty()) {
//empty movie object
...
}
In setData you always set the value of mov[0]. The class member i will never change (loop variable hides it). You do not use the parameter m to set the data.
Change your setData to
m.setName(name);
m.setDirector(director);
m.setfileSize(fileSize);
m.setDuration(duration);

Issue with a method for a library of objects

I'm trying to make a program that creates a library of different books, I have set a number of copies for each item in the library and every time I check out an Item I want it to deduct 1 copy from only the particular object I check out but instead it takes a copy away from all the objects. not sure how to fix the problem.
public abstract class Item{
private int identify;
private String title;
private int copies;
public Item(){
identify=0;
title="N/A";
copies=0;
}
public Item(int id, int copy, String t){
identify=id;
copies=copy;
title=t;
}
public void setIdentificationNumber(int id){
identify = id;
}
public void setTitle(String t){
title=t;
}
public void setNumberCopies(int num){
copies=num;
}
public int getIdentificationNumber(){
return identify;
}
public String getTitle(){
return title;
}
public int getNumberCopies(){
return copies;
}
public void checkOut(){
if(copies>0){
copies-=1;
System.out.println("You have checked out "+title+". Thank You");
}
else{
System.out.println("All copies of "+title+" are checked out!");
}
}
public void checkIn(){
copies+=1;
}
}
The problem may also be in my client method I have posted the code for that as well below.
import java.util.Arrays;
import java.util.Scanner;
public class Library{
static String title;
static String author;
static int id;
static int copies;
static String date;
static Book[] database = new Book[100];
static int count=0;
public static void main(String[] args){
int i;
Scanner s = new Scanner(System.in);
do{
addBook();
System.out.println("would you like to add another book?");
i=s.nextInt();
}while(i == 0);
database[0].viewDetails();
database[1].viewDetails();
checkingOut();
database[0].viewDetails();
database[1].viewDetails();
}
public static void addBook(){
Scanner s = new Scanner(System.in);
System.out.println("Enter the title of the book you want to add to the collection");
title=s.nextLine();
System.out.println("Enter the author of the book you want to add to the collection");
author=s.nextLine();
System.out.println("Enter the publishing date of the book you want to add to the collection");
date=s.nextLine();
System.out.println("Enter the ID number of the book you want to add to the collection");
id=s.nextInt();
System.out.println("Enter the the number of copies that will be added into the collection");
copies=s.nextInt();
Book Book1 = new Book(date, author, copies, id, title);
database[count] = Book1;
count++;
}
public static void checkingOut(){
boolean found=false;
int idSearch;
int i=0;
Scanner s = new Scanner(System.in);
System.out.println("Enter the ID number of the book you want to check out");
idSearch=s.nextInt();
while(i<database.length && found!=true){
if(database[i].getIdentificationNumber() == idSearch){
found = true;
}
i++;
}
if(found==true){
database[i].checkOut();
System.out.println("There are "+database[i].getNumberCopies()+" copies left");
}
else{System.out.println("There is no book with that ID number!");}
}
}
In my addBook method I create a new object called book1 every time I make a new book, so I think that it may be changing all of the book objects every time I add a book. I'm not really sure of a better way to write the method.
here is my method for book also
public class Book extends WrittenItem{
public Book(){
super();
}
public Book(String date, String a, int copy, int id, String t){
super(a, date, copy, id, t);
}
public void viewDetails(){
System.out.println("ID: "+getIdentificationNumber()+"\nTitle: "+getTitle()+"\nAuthor: "+getAuthor()+" Date written: "+getDate()+"\nCopies available: "+getNumberCopies());
}
}
Any help would be greatly appreciated.
I can't 100% tell from your code, but I'm assuming Book extends Item. In that case, try something like this for Book constructor
public class Book extends Item {
String author;
String date;
public Book(String date, String author, int copies, int id, String title) {
super(id, copies, title); // Item constructor matches this super() call
// public Item(int id, int copy, String t)
this.author = author;
this.date = date;
}
}
You want Book to have the same copies at Item. So when you checkOut(), the Item number equals you input from the Book constructor. If you don't put the super() in the constructor, your Item copies will remain 0 and you will always get System.out.println("All copies of "+title+" are checked out!"); because copies is never > 0.
If your book is something like this,
public class Book extends Item {
private String date;
private String author;
public Book() {
}
public Book(String date, String author, int copies, int id, String title) {
super(id, copies, title);
this.author = author;
this.date = date;
}
void viewDetails() {
System.out.println("date:" + date + " author:" + author + " copies:" + getNumberCopies() + " id:" + getIdentificationNumber() + " title:" + getTitle());
}
}
Then your code should work fine, as i've tested, if you also add a break in your checkingOut() method,
public static void checkingOut() {
boolean found = false;
int idSearch;
int i = 0;
Scanner s = new Scanner(System.in);
System.out.println("Enter the ID number of the book you want to check out");
idSearch = s.nextInt();
while (i < database.length && found != true) {
if (database[i].getIdentificationNumber() == idSearch) {
found = true;
break; //add this
}
i++;
}
if (found == true) {
database[i].checkOut();
System.out.println("There are " + database[i].getNumberCopies() + " copies left");
} else {
System.out.println("There is no book with that ID number!");
}
}

How to use more than one method?

So, I've got to write an invoice for a video store that has a Customer class which takes six attributes, the customer name (string), the street address (string), the city(String), the state(string), the zip code(string), and the telephone number. I had to use a parameterized constructor that receives the attributes as parameters as well as provide getters and setters. I believe I did this correctly.
Next I had to make a Video class that had four attributes, the video name (string), the year the video was released(integer), the video copy number(integer), and the daily rental rate(double). I had to do a parameterized constructor and getters and setters for this as well.
The problems start on my Invoice class which is to represent the rental of a video to a given customer, it is not finished, but is supposed to have four attributes, the customer renting the video, the video being rented, the date it was rented(as a inputted string), and the daily rental rate(double). It was also supposed to have three methods, the subtotal, the tax and the total. My problem is I've got the preset methods for the customers and the videos setup, I just have no clue how to effectively use them in an if statement. I don't know what I would put in my fourth test class to allow this to work. I am all but lost at this point, any push in the right direction would be greatly appreciated. here are my classes.
Customer:
public class Customer {
private String customerName;
private String streetAddress;
private String custCity;
private String custState;
private String custZip;
private String custPhone;
public Customer(String customerName, String streetAddress, String custCity, String custState, String custZip,
String custPhone) {
super();
this.customerName = customerName;
this.streetAddress = streetAddress;
this.custCity = custCity;
this.custState = custState;
this.custZip = custZip;
this.custPhone = custPhone;
}
public String getCustomerName() {
return customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
public String getStreetAddress() {
return streetAddress;
}
public void setStreetAddress(String streetAddress) {
this.streetAddress = streetAddress;
}
public String getCustCity() {
return custCity;
}
public void setCustCity(String custCity) {
this.custCity = custCity;
}
public String getCustState() {
return custState;
}
public void setCustState(String custState) {
this.custState = custState;
}
public String getCustZip() {
return custZip;
}
public void setCustZip(String custZip) {
this.custZip = custZip;
}
public String getCustPhone() {
return custPhone;
}
public void setCustPhone(String custPhone) {
this.custPhone = custPhone;
}
}
Video:
public class Video {
private String videoName;
private int videoYear;
private int copyNum;
private double rentalRate;
public Video(String videoName, int videoYear, int copyNum, double rentalRate) {
super();
this.videoName = videoName;
this.videoYear = videoYear;
this.copyNum = copyNum;
this.rentalRate = rentalRate;
}
public String getVideoName() {
return videoName;
}
public void setVideoName(String videoName) {
this.videoName = videoName;
}
public int getVideoYear() {
return videoYear;
}
public void setVideoYear(int videoYear) {
this.videoYear = videoYear;
}
public int getCopyNum() {
return copyNum;
}
public void setCopyNum(int copyNum) {
this.copyNum = copyNum;
}
public double getRentalRate() {
return rentalRate;
}
public void setRentalRate(double rentalRate) {
this.rentalRate = rentalRate;
}
Invoice (incomplete) :
import java.util.Scanner;
public class Invoice {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
Customer Brandon = new Customer("Brandon James" , "112 Oak Street"
, "CityVille" , "Alabama" , "18229",
"912-2248");
Customer Judy = new Customer("Judy Vermooth" , "8008 Ribbit Ln.",
"Metropolis" , "Pennsylvania" , "24057", "241-8009");
Video Easter = new Video("Easter 2", 2002, 4, 2.49);
Video DareDevil3 = new Video ("Dare Devil 3", 2012, 2, 3.62);
if( Prog4.newRental = "Brandon"){
Customer Brandon = newCust
}
}
}
Prog4(incomplete):
import java.util.*;
public class Prog4 {
private String newRental;
private String vidName;
private String rentalDate;
private String daysRented;
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.println("Enter Customer Name: ");
String newRental = in.nextLine();
System.out.println("Enter Video Name: ");
String vidName = in.nextLine();
System.out.println("Enter Rental date in mm/dd/yyyy format: ");
String rentalDate = in.nextLine();
System.out.println("Enter Number of Days Rented");
int daysRented = in.nextInt();
}
public String getNewRental() {
return newRental;
}
public void setNewRental(String newRental) {
this.newRental = newRental;
}
public String getVidName() {
return vidName;
}
public void setVidName(String vidName) {
this.vidName = vidName;
}
public String getRentalDate() {
return rentalDate;
}
public void setRentalDate(String rentalDate) {
this.rentalDate = rentalDate;
}
public String getDaysRented() {
return daysRented;
}
public void setDaysRented(String daysRented) {
this.daysRented = daysRented;
}
}

Categories

Resources