how to increment the id and take a lengthy description in java - 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;

Related

Difficulty setting and updating objects in a Sorted ArrayList [duplicate]

This question already has answers here:
method in class cannot be applied to given types
(7 answers)
Closed 2 years ago.
I wish to be able to update information about objects entered by a user. I would like the user to enter a book name and user name to take out the book, as well as being able to return it with the same information. The objects have to be inserted into the right place in my sortedarraylists. Each user is assumed to be unique and each book can only be taken out by one user (who can take out up to 3 books).
When I try to compile my code, I get this error message:
java: method issueBook in class Driver cannot be applied to given types;
required: Book,User
found: no arguments
reason: actual and formal argument lists differ in length
This corresponds to issueBook(); in case i of my menu.
I also have User and Book classes that implement Comparable<Book> etc. I tried to omit as much irrelevant code as I could, such as the filereader to scan in new user and book objects. I included the book and user classes in case they need to be looked at (I think they are mostly fine). Please let me know if you need any more details however.
import java.io.*;
import java.util.Scanner;
public class Driver {
static Scanner sc = new Scanner(System.in);
private static void mainMenu() {
System.out.println("------------------------------\n"+
"f: Finish running the program\n" +
"b -Display on the screen the information about all the books in the library\n" +
"u -Display on the screen the information about all the users.\n" +
"i -Update the stored data when a book is issued to a user\n" +
"r -Update the stored data when a user returns a book to the library\n" +
"------------------------------\n" +
"Type a letter and press Enter\n");
}
private static User readNames() throws User.InvalidBookLimitException {
System.out.println("Enter the user's firstname: ");
String firstName = sc.next();
System.out.println("Enter the user's surname: ");
String surName = sc.next();
sc.nextLine(); //TODO check this
return new User(firstName, surName, 0);
}
private static User readUserData(User user) throws User.InvalidBookLimitException {
User u = readNames();
System.out.println("Enter " + user + "'s age, and press Enter");
int numberOfBooks = sc.nextInt();
sc.nextLine();
return new User(u.getFirstName(), u.getSurName(),u.getNumberOfBooks());
}
private static Book readBookName (){
System.out.println("Type in the name of the book");
String bookName = sc.nextLine();
return new Book(bookName);
}
/* public SortedArrayList<User> sortedUsers = new SortedArrayList<>(); public SortedArrayList<Book> sortedBooks = new SortedArrayList<>();*/
//If this part is commented out, I get errors since I can't seem to access the arraylists in the
// main method for the issueBook/returnBook methods.
public void issueBook(Book book, User user){
for (Book b : sortedBooks){
if(b.equals(book)){
b.loanStatus(true);
/*b.setLoanerNames(user);*/ b.setLoanerNames("John", "Doe");
break;
}
}
for (User u: sortedUsers){
if(u.equals(user)){
u.setNumberOfBooks(u.getNumberOfBooks()+1);
}
}
}
public void returnBook(Book book, User user){
for (Book b : sortedBooks){
if(b.equals(book)){
b.loanStatus(false);
b.setLoanerNames(null, null);
break;
} for (User u: sortedUsers){
if(u.equals(user)){
u.setNumberOfBooks(u.getNumberOfBooks()-1);
}
}
}
}
public static <E> void main(String[] args) throws FileNotFoundException, User.InvalidBookLimitException {
//These SortedArrayLists have been derived from the sorted arraylist class
SortedArrayList<User> sortedUsers = new SortedArrayList<>();
SortedArrayList<Book> sortedBooks = new SortedArrayList<>();
mainMenu(); //main menu printing method
char ch = sc.next().charAt(0);
sc.nextLine();
while (ch !='f') //the program ends as desired if f is pressed
{ switch(ch){
case 'b':
System.out.println("Displaying information about all books in the library: ");
/*for (Object item : sortedBooks) {
System.out.println(sortedBooks.toString());
}*/
System.out.println(sortedBooks/*.toString()*/);
break;
case 'u':
System.out.println("Displaying information about all users");
System.out.println(sortedUsers/*.toString()*/);
break;
case 'i':
System.out.println("Enter the loaning out data. ");
System.out.println("Enter the user's first name and surname: ");
readNames();
System.out.println("Enter the name of the book: ");
readBookName();
issueBook();
or maybe if(u1.compareTo(u2) == 0)*/
break;
case 'r':
System.out.println("Please the details of the book to be returned: ");
/*Book b = new Book("test1", "test2", true, "lol","lol2");*/
//this was just a test and didn't work
/*returnBook(b);*/
break;
default:
System.out.println("Invalid input, please enter f, b, i or r");
}
mainMenu();
ch = sc.next().charAt(0);
sc.nextLine();
}
}
}
My sorted arraylist class with a (working) insert method:
import java.util.ArrayList;
public class SortedArrayList<E extends Comparable<E>> extends ArrayList<E> {
//no need for a generic in the insert method as this has been declared in the class
public void insert(E value) {
if (this.size() == 0) {
this.add(value);
return; }
for (int i = 0; i < this.size(); i++) {
int comparison = value.compareTo((E) this.get(i));
if (comparison < 0) {
this.add(i, value);
return; }
if (comparison == 0) {
return; }
}
this.add(value);
}
User class:
import java.io.PrintWriter;
public class User implements Comparable<User> {
private String firstName;
private String surName;
private int numberOfBooks;
public User(){
firstName = "";
surName = "";
numberOfBooks = 0;
}
public class InvalidBookLimitException extends Exception{
public InvalidBookLimitException(){
super("Invalid number of books");
}
}
public User(String name1, String name2, int books) throws InvalidBookLimitException {
this.firstName = name1;
this.surName = name2;
if (books>3) throw new InvalidBookLimitException ();
this.numberOfBooks = books;
}
public String getFirstName() {
return firstName;
}
public String getSurName(){
return surName;
}
public int getNumberOfBooks(){
return numberOfBooks;
}
public boolean borrowMoreBooks(){
return numberOfBooks < 3;
}
public void setNumberOfBooks(int numberOfBooks){
this.numberOfBooks=numberOfBooks;
}
public void setUser(String name1, String name2, int books){
firstName = name1;
surName = name2;
numberOfBooks = books;
}
public boolean userNameTest (User otherUser){
return (firstName.equals(otherUser.firstName) && surName.equals(otherUser.surName));
}
/* public boolean loanAnotherBook(){
return !(numberOfBooks<3);
numberOfBooks++;
}*/
public void printName(PrintWriter f){f.println(firstName+ " " + surName);}
/*
public void setUser(User user) {
if (loanStatus == false){
loanStatus = Driver.readNameInput();
loanStatus = true;
}
}*/
#Override
public String toString(){
return "Name: " + firstName + " " + surName + " | Number of books: " + numberOfBooks;
}
public int compareTo(User u) {
/* int snCmp = surName.compareTo(u.surName);
if (snCmp != 0)
return snCmp;
else{
int fnCmp = firstName.compareTo(u.firstName);
if (fnCmp !=0)
return fnCmp;
}*/
int fnCmp = firstName.compareTo(u.firstName);
if (fnCmp != 0) return fnCmp;
int snCmp= surName.compareTo(u.surName);
if (snCmp !=0) return snCmp;
else return numberOfBooks -u.numberOfBooks;
}
#Override
public boolean equals(Object obj) {
return super.equals(obj);
}
}
Book class:
public class Book implements Comparable<Book>{
public String bookName;
public String authorName;
public boolean loanStatus;
public String loanerFirstName;
public String loanerSurName;
//if boolean loanStatus == true private string loaner name
public Book(){
bookName = "";
authorName = "";
loanStatus = false;
loanerFirstName = null;
loanerSurName = null;
}
Book(String book, String author, boolean loanStatus, String loanerFirstName, String loanerSurName) {
this.bookName = book;
this.authorName = author;
this.loanStatus = loanStatus;
this.loanerFirstName = loanerFirstName;
this.loanerSurName = loanerSurName;
}
Book(String book){
this.bookName=book;
}
public String getBookName(){
return bookName;
}
public String getAuthorName(){
return bookName;
}
public boolean getLoanStatus(){
return loanStatus;
}
public String getLoanerFirstName(){
return loanerFirstName;
}
public String getLoanerSurName(){
return loanerSurName;
}
public void setBook(String book, String author, boolean loanStatus, String loanerFirstName, String loanerSurName){
bookName = book;
authorName = author;
loanStatus = loanStatus;
loanerFirstName = loanerFirstName;
loanerSurName = loanerSurName;
}
public void setBookName(String bookName){
this.bookName=bookName;
}
public void loanStatus(boolean loanStatus){
this.loanStatus=loanStatus;
}
public void setLoanerNames(String loanerFirstName, String loanerSurName){
this.loanerFirstName=loanerFirstName;
this.loanerSurName=loanerSurName;
}
/* public boolean nameTest (User otherUser){
return (loanerFirstName.equals(otherUser.loanerFirstName)&& loanerSurName.equals(otherUser.loanerSurName));
}
*/
public String toString(){
return "Book: " + bookName + " | Author: " + authorName + " | Loan status: " + loanStatus + " | Loaned to: " + loanerFirstName + " " + loanerSurName ;
}
//this may be redundant TODO
/* public void setLoanStatus(User user){
loanStatus = false;
}*/
//This compare method allows new user objects to be compared to ones in the
#Override //sortedArrayList, enabling the insertion method.
public int compareTo(Book b) {
int bnCmp = bookName.compareTo(b.bookName);
if (bnCmp != 0) return bnCmp;
int anCmp= authorName.compareTo(b.authorName);
if (anCmp !=0) return anCmp;
// int lsCmp= loanStatus.(b.loanStatus);
// if (lsCmp !=0) return lsCmp;
int lrfnCmp =loanerFirstName.compareTo(b.loanerFirstName);
if (lrfnCmp !=0) return lrfnCmp;
int lrlnCmp =loanerSurName.compareTo(b.loanerSurName);
if (lrlnCmp !=0) return lrlnCmp;
else return 0;
}
}
User user = readNames();
Book book = readBookName();
issueBook(book, user);
You have to pass the user and book which you have created while calling the issueBook method.

Keep a Record of User Input - 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!

Abstract class return

Sorry if this is something small. I have created an abstract class with some child classes. A controller class creates a object of type abstract class of requested child class type and returns the abstract class implemented.
The child classes have specific attributes for them. I can't access those attributes of the returned object since this is of the abstract class default type, so i tried casting. But this give an error "item.Default cannot be cast to item.cloth"
How to fix it?
Code:
public class testMain {
public void main(int id) {
Product test;
switch(ProductController.getCategory(id)) {
case "Cloth":
test = (cloth) ProductController.getProduct(id);
break;
case "Wear":
test = (wear) ProductController.getProduct(id);
break;
default:
test = (Default) ProductController.getProduct(id);
}
System.out.println("Product No : " + test.ProductNo);
System.out.println("Title : " + test.Title);
System.out.println("Description : " + test.Desc);
System.out.println("Short Description : " + test.ShortDesc);
System.out.println("Regular Price : " + test.RegularPrice);
System.out.println("Sale Price : " + test.SalePrice);
System.out.println("Category : " + test.Category);
if(((String) test.Category).split(",")[1].contentEquals("cloth")) {
System.out.println("Size : " + ((cloth) test).size);
System.out.println("Age : " + ((cloth) test).age);
}else if(((String) test.Category).split(",")[1].contentEquals("wear")) {
System.out.println("Brand : " + ((wear) test).Brand);
}
}
}
public class ProductController {
private static ProductDB prodDB = new ProductDB();
public static Product getProduct(int prodID) {
Product product;
List<Object> prodTemp = prodDB.getProductDetails(prodID);
String Category[] = ((String) prodTemp.get(6)).split(",");
switch(Category[1]) {
case "Cloth":
product = new cloth(...);
break;
case "Wear":
product = new wear(...);
break;
default:
product = new Default(...);
}
return product;
}
public static String getCategory(int prodID) {
return prodDB.getCategory(prodID).split(",")[1];
}
}
public abstract class Product {
public int ProductNo;
public String Title;
public String Desc;
public String ShortDesc;
public float RegularPrice;
public float SalePrice;
public boolean StockStatus;
public String Category;
public void setRegularPrice(float regularPrice) {
RegularPrice = regularPrice;
setSalePrice(regularPrice);
}
protected abstract void setSalePrice(float regularPrice2);
public float getSalePrice() {
return SalePrice;
}
public void setStockStatus(boolean stockStatus) {
StockStatus = stockStatus;
}
public boolean isInStock() {
return StockStatus;
}
public Product(int productNo2, String title, String desc, String shortDesc, float regularPrice, boolean stock, String Category) {
ProductNo = productNo2;
Title = title;
Desc = desc;
ShortDesc = shortDesc;
setRegularPrice(regularPrice);
StockStatus = stock;
this.Category = Category;
}
public Product(int productNo, String title, String desc, String shortDesc) {
ProductNo = productNo;
Title = title;
Desc = desc;
ShortDesc = shortDesc;
}
public Product(int productNo, String title, String desc, String shortDesc, float regularPrice) {
ProductNo = productNo;
Title = title;
Desc = desc;
ShortDesc = shortDesc;
setRegularPrice(regularPrice);
}
}
public class cloth extends Product{
public String size;
public int age;
public cloth(int productNo, String title, String desc, String shortDesc, float regularPrice, boolean stock, String Category, String size, int age) {
super(productNo, title, desc, shortDesc, regularPrice, stock, Category);
this.size = size;
this.age = age;
}
#Override
protected void setSalePrice(float regularPrice2) {
SalePrice = (float) (regularPrice2 * 0.85);
}
}
You have to put the break after every switch case. If you test this code:
public static void main(String[] args) {
int test = 2;
switch (test){
case 1:
System.out.println("One");
case 2:
System.out.println("Two");
case 3:
System.out.println("Three");
default:
System.out.println("Default");
}
}
you will get this output:
Two
Three
Default
So the above code has to be changed like this:
public static void main(String[] args) {
int test = 2;
switch (test){
case 1:
System.out.println("One");
break;
case 2:
System.out.println("Two");
break;
case 3:
System.out.println("Three");
break;
default:
System.out.println("Default");
}
}

Method Chaining to Print in an Compostion model with arrays

I am a student working on a project creating classes with arrays to model composition. I have assume I have everything right so far but it seem that I am getting a problem with my print statement in the driver class. I am not sure if it about the way I am method chaining the two together. Any information would be thankful.
public class MyWord
{
private String word;
public MyWord(){
word = "Null";
}
public MyWord(String s){
word = s;
}
public String getWord(){
return word;
}
public void setWord(String w){
word = w;
}
public void print(){
System.out.println(word);
}
}
public class Page
{
private MyWord[] words = new MyWord[5];
private int pageNumber;
public Page(){
MyWord words[] = {} ;
pageNumber = 0;
}
public Page(MyWord[] a, int b){
words = a;
pageNumber = b;
}
public MyWord[] getWord(){
return words;
}
public int getPageNumber(){
return pageNumber;
}
public void setMyWord(MyWord[] a){
words = a;
}
public void setPageNumber(int b){
pageNumber = b;
}
public void print(){
System.out.print(" Page Number: " + pageNumber + " " + words);
}
}
public class Book
{
private Page[] p = new Page[5];
private String title;
public Book(){
Page[] p = {};
title = " ";
}
public Book(Page[] pa, String ti){
p = pa;
title = ti;
}
public Page[] getPage(){
return p;
}
public String getTitle(){
return title;
}
public void setPage(Page[] x){
p = x;
}
public void setTitle(String y){
title = y;
}
public void print(){
System.out.print("Book info:" + p + " " + title);
}
}
public class Series
{
private Book bookOne, bookTwo, bookThree;
private double price;
public Series(){
bookOne = null;
bookTwo = null;
bookThree = null;
price = 0;
}
public Series(Book one, Book two, Book three, double p){
bookOne = one;
bookTwo = two;
bookThree = three;
price = p;
}
public Book getBookTwo(){
return bookTwo;
}
public Book getBookOne(){
return bookOne;
}
public Book getBookThree(){
return bookThree;
}
public double getPrice(){
return price;
}
public void setBookOne(Book bookOne){
this.bookOne = bookOne;
}
public void setBookTwo(Book bookTwo){
this.bookTwo = bookTwo;
}
public void setBookThree(Book bookThree){
this.bookThree = bookThree;
}
public void setPrice(double price){
this.price = price;
}
public void print(){
System.out.println("Series info");
System.out.println("Book one:" + bookOne + " Book Two: " +bookTwo
+ " Book Three: " + bookThree + "Price: " + price);
}
}
public class Driver
{
public static void main(String args[]){
MyWord[] w1 = new MyWord[2];
w1[0] = new MyWord("Hello");
w1[1] = new MyWord("Hola");
Page[] p = new Page[2];
p[0] = new Page(w1, 20);
p.print();
}
}
p is of type Page[], i.e. "array of Page". And arrays don't have a print() method. So the statement p.print() doesn't compile (you should have said that in your question, and joined the exact error message).
To print all the pages of the array, you need to loop over the array:
for (Page page : p) {
page.print();
}
Please avoid single-letter variables, and use a plural form for arrays and collections: Page[] pages = new Page[2];

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

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

Categories

Resources