having trouble setting up an array for my program - java

I am making a program for a library; the library contains different items such as book, videos, journals, ect...
I have a class called item with basic methods for every item in the library, and my classes for book, video, journal and all other items extend Item. I want to make an array to contain all of the items in the library so people can search for a specific item, it will find it in the array and display the info for that item.
The problem I'm having is that when I create an array of type Item I can only call methods of the Item class and I can't call the new methods I made for book in the book class or for journal in the journal class.
So I'm forced to have separate arrays for each of the different types of Items.
Is there a way to have just one array that can call methods from all the different classes for each item?
You can see my code below; I have only attached the code for my tester class where the array is, let me know if you need to see the code for the other classes. I would appreciate any help.
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 Video[] database2 = new Video[100];
static Journal[] database3 = new Journal[100];
static CD[] database4 = new CD[100];
static int count=0;
public static void main(String[] args){
int i;
Scanner s = new Scanner(System.in);
do{
System.out.println("type the adjacent number to preform that process.\n1: Add an item\n2: Checkout an item\n0: Exit program");
i=s.nextInt();
switch(i){
case 1:
addItem();
break;
case 2:
break;
}
}while(i != 0);
database[0].viewDetails();
database[1].viewDetails();
checkingOut();
database[0].viewDetails();
database[1].viewDetails();
}
public static void addItem(){
int i;
Scanner s = new Scanner(System.in);
do{
System.out.println("type the adjacent number to add the item.\n1: Book\n2: Video\n3: Journal\n4: CD\n Type 0 to stop");
i=s.nextInt();
switch(i){
case 1:
addBook();
break;
case 2:
addVideo();
break;
case 3:
addJournal();
break;
case 4:
addCD();
break;
}
}while(i != 0);
}
public static void addBook(){
String title;
String author;
int id;
int copies;
String date;
int count=0;
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 addJournal(){
String title;
String author;
int id;
int copies;
String date;
int count=0;
Scanner s = new Scanner(System.in);
System.out.println("Enter the title of the journal you want to add to the collection");
title=s.nextLine();
System.out.println("Enter the author of the journal you want to add to the collection");
author=s.nextLine();
System.out.println("Enter the publishing date of the journal you want to add to the collection");
date=s.nextLine();
System.out.println("Enter the ID number of the journal 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();
Journal Journal1 = new Journal(date, author, copies, id, title);
database3[count] = Journal1;
count++;
}
public static void addCD(){
String title;
String art;
String genre;
int id;
int copies;
int date;
int count=0;
Scanner s = new Scanner(System.in);
System.out.println("Enter the title of the cd you want to add to the collection");
title=s.nextLine();
System.out.println("Enter the artist of the cd you want to add to the collection");
art=s.nextLine();
System.out.println("Enter the release year of the cd you want to add to the collection");
date=s.nextInt();
System.out.println("Enter the genre of the cd you want to add to the collection");
genre=s.nextLine();
System.out.println("Enter the ID number of the cd 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();
CD CD1 = new CD(date, copies, id, title, art, genre);
database4[count] = CD1;
count++;
}
public static void addVideo(){
String title;
String director;
int id;
int copies;
int date;
String genre;
int count=0;
Scanner s = new Scanner(System.in);
System.out.println("Enter the title of the video you want to add to the collection");
title=s.nextLine();
System.out.println("Enter the director of the cd you want to add to the collection");
director=s.nextLine();
System.out.println("Enter the release year of the cd you want to add to the collection");
date=s.nextInt();
System.out.println("Enter the genre of the video you want to add to the collection");
genre=s.nextLine();
System.out.println("Enter the ID number of the video 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();
Video Video1 = new Video(date, copies, id, title, director, genre);
database2[count] = Video1;
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;
break;
}
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!");}
}
}

You could check the type and cast it to that type to gain access to the additional methods.
public static void main(String args[]){
for(Item item : itemList){
if(item instanceof Book){
Book book = (Book) item;
book.someBookMethod();
}
}
}
though using instanceof is considered harmful
A better design would be to make Item abstract and create the methods common to all children, such as add()
public abstract class Item{
public void add();
public void viewDetails();
}
class Book extends Item{
public void add(){
//fun stuff
}
public void viewDetails(){
//moar serious business logic
}
}
....
public static void main(String args[]){
for(Item item : itemList){
item.add();
}
}

Related

When I print out my list it prints out null for all my values..... How do I fix this issue???? I want to learn how to fix this issue for future

I made a list for my teachers and print out the list. The list prints, but the problem is that my list prints out null for all values in my list. It gives me null for first name, last name, id and course. What am I doing wrong??? How can I fix this? I want to be able to print out my actual values in my list of teachers. I don't see what could be the issue if I'm being totally honest. I add the first name, last name, id and course to the teacher list correctly. So, what am I missing?
Error:
Main.java code:
package SchoolSystem;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.concurrent.TimeUnit;
public class main{
public static void main(String[] args) throws InterruptedException {
int ch; //user choice
teacher teachers = new teacher();
student students = new student();
//add teachers
List<teacher> teach = new ArrayList<>();
teach.add(new teacher(teachers.first_name, teachers.last_name, teachers.teacher_id, teachers.course));
Scanner sc = new Scanner(System.in);
loop : while (true) {
//menu
System.out.println("");
System.out.println("1: Add Teacher"); //user can add a teachers name, id, and course
System.out.println("2: Add Student"); //user can add a students name, id, courses, and GPA
System.out.println("3: All Teachers"); //user can access teacher list and change items
System.out.println("4: All students"); //user can access student list and change items
System.out.println("5: Exit Program");
System.out.print("Enter your choice: ");
ch = sc.nextInt();
System.out.println("");
switch (ch) {
case 1:
System.out.println("Enter teacher's first name: ");
teachers.first_name = sc.next();
System.out.println("Enter teacher's last name: ");
teachers.last_name = sc.next();
System.out.println("Enter teacher's id: ");
teachers.teacher_id = sc.next();
System.out.println("Enter teacher's course: ");
teachers.course = sc.next();
break;
case 2:
System.out.println("Enter student's first name: ");
students.first_name = sc.next();
System.out.println("Enter student's last name: ");
students.last_name = sc.next();
System.out.println("Enter student's id: ");
students.student_id = sc.next();
System.out.println("Enter student's course: ");
students.course = sc.next();
break;
case 3:
System.out.println("-----------------------------------------------------------------------------");
System.out.printf("%1s %20s %5s %5s", "FIRSTNAME", "LASTNAME", "ID", "COURSE");
System.out.println();
System.out.println("-----------------------------------------------------------------------------");
for(teacher teacher: teach){
System.out.format("%1s %20s %5s %5s",
teacher.getFirstName(), teacher.getLastName(), teacher.getId(), teacher.getCourse());
System.out.println();
}
System.out.println("-----------------------------------------------------------------------------");
break;
case 4:
//null
break;
case 5:
/*
System.out.println("Exiting Program....");
TimeUnit.SECONDS.sleep(3);
System.out.println("Goodbye!");
break loop;
*/
break;
default:
//System.out.println("Invalid choice! Please enter an option (1 - 5)");
}
}
}
}
Teacher.java code:
package SchoolSystem;
public class teacher {
public teacher() {
//null
}
public String first_name;
public String last_name;
public String teacher_id;
public String course;
public teacher(String first_name, String last_name, String teacher_id, String course) {
this.first_name = first_name;
this.last_name = last_name;
this.teacher_id = teacher_id;
this.course = course;
}
//return firstname
public String getFirstName() {
return first_name;
}
//return lastname
public String getLastName() {
return last_name;
}
//return teacherId
public String getId() {
return teacher_id;
}
//return course
public String getCourse() {
return course;
}
}
in Teacher Class you must add setters
public class Teacher {
public Teacher() {
//null
}
public String first_name;
public String last_name;
public String teacher_id;
public String course;
public Teacher(String first_name, String last_name, String teacher_id, String course) {
this.first_name = first_name;
this.last_name = last_name;
this.teacher_id = teacher_id;
this.course = course;
}
//return firstname
public String getFirstName() {
return first_name;
}
public void setFirstName(String firstName) {
this.first_name = firstName;
}
//return lastname
public String getLastName() {
return last_name;
}
public void setLastName(String lastName) {
this.last_name = lastName;
}
//return teacherId
public String getId() {
return teacher_id;
}
public void setId(String id) {
this.teacher_id = id;
}
//return course
public String getCourse() {
return course;
}
public void setCourse(String course) {
this.course = course;
}
}
in Main
delete this line
teach.add(new Teacher(teachers.getFirstName(), teacher.getLastName(), teacher.getId(), teacher.getCourse()));
and write:
int ch; //user choice
//add teachers
List<Teacher> teach = new ArrayList<>();
Scanner sc = new Scanner(System.in);
// teach.add(new Teacher(teachers.getFirstName(), teacher.getLastName(), teacher.getId(), teacher.getCourse()));
loop : while (true) {
//menu
System.out.println("");
System.out.println("1: Add Teacher"); //user can add a teachers name, id, and course
System.out.println("2: Add Student"); //user can add a students name, id, courses, and GPA
System.out.println("3: All Teachers"); //user can access teacher list and change items
System.out.println("4: All students"); //user can access student list and change items
System.out.println("5: Exit Program");
System.out.print("Enter your choice: ");
ch = sc.nextInt();
System.out.println("");
switch (ch) {
case 1:
Teacher teachers = new Teacher();
System.out.println("Enter teacher's first name: ");
teachers.setFirstName(sc.next());
System.out.println("Enter teacher's last name: ");
teachers.setLastName(sc.next());
System.out.println("Enter teacher's id: ");
teachers.setId(sc.next() );
System.out.println("Enter teacher's course: ");
teachers.setCourse (sc.next());
teach.add(teachers);
break;
case 2:
// .....
use setters to add values and add "teachers" oject to List
teach.add(teachers);
You are having OOP issues with your code.
teacher teachers = new teacher();
...
List<teacher> teach = new ArrayList<>();
teach.add(new teacher(teachers.first_name, teachers.last_name, teachers.teacher_id, teachers.course));
This snippet takes a new instance of a teacher and then creates a brand new instance of teacher to add to the list. These are 2 distinct objects. I'm assuming you are coming from C or C++ and you are thinking of them as pointers? Fortunately, that's not how Java works.
You can simply add the "teachers" variable to the "teach" list. Then when you later update the "teachers" object, the data will be available in the "teach" list.
The caveat to this is you need to instantiate a new object for "teachers" inside the loop, as well as moving the modified teach.add(teachers); into the loop.
List<teacher> teach = new ArrayList<>();
List<student> stud = new ArrayList<>();
Scanner sc = new Scanner(System.in);
loop : while (true) {
...
switch (ch) {
case 1:
teacher teachers = new teacher();
...
teach.add(teachers);
break;
case 2:
student students = new student();
...
stud.Add(students);
break;
...
Now you have a new teacher object for every teacher as well as a list containing only valid data, rather than empty objects.
This works because "teach" now contains a reference to the instance of "teachers". This is similar to the pointers of C and C++ I mentioned earlier. In this case, you have a reference to the whole object, not to the individual properties of the object you were trying to have earlier.
Think of an object as a piece of paper and a list as a box. You can put all kinds of data on the paper, then put the piece of paper in the box. When you need a new object, you get a new piece of paper, write the data on it, and add it to the box. Then when you want to update an object, you find it in the box and update the data. It's that simple. You can have a complex object where it has instances of other objects in it, but that's beyond the scope of your question.
On a side note
Classes teacher and student should be capitalized as Teacher and Student. The list of Teachers should be named "teachers" and a single Teacher object should be named "teacher", or something that won't be confused with the class name. In general, lists should be plural and a singular instance should be singular.

Trouble with objected oriented programming, creating multiple instances

I am new to OOP and Java Classes, so bear with me.
I am trying to create a class that allows me to store data about books, specifically the fields: Title, Author, Year published, Page count, Genre
Then with that class, I wish to have a main program that runs, asks for a number of books to enter and then allows the user to input the information for each book. Then, a summary is printed for each book.
I have attempted to program a class "bookClass" that allows input of the book information and then a class "bookTest" that creates an array using the bookClass.
This is the bookClass:
public class bookClass {
private String title;
private String author;
private String year;
private String pageCount;
private String genre;
private static int bookCount;
public bookClass(String title, String author, String year, String pageCount, String genre) {
this.setTitle(title);
this.setAuthor(author);
this.setYear(year);
this.setPageCount(pageCount);
this.setGenre(genre);
bookCount++;
}
public void setTitle(String title) {
this.title = title;
}
public void setAuthor(String author) {
this.author = author;
}
public void setYear(String year) {
this.year = year;
}
public void setPageCount(String pageCount) {
this.pageCount = pageCount;
}
public void setGenre(String genre) {
this.genre = genre;
}
public String getTitle() {
return title;
}
public String getAuthor() {
return author;
}
public String getYear() {
return year;
}
public String getPageCount() {
return pageCount;
}
public String getGenre() {
return genre;
}
public int getBookCount() {
return bookCount
}
}
This is the main class:
import java.util.*;
public class bookTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
System.out.print("How many books would you like to enter: ");
int bookAmount = input.nextInt(); input.nextLine();
String[][] books2DArray = new String[bookAmount][5];
for (String[] books1DArray: books2DArray) {
System.out.print("Please enter the title: ");
String title = input.nextLine();
System.out.print("Please enter the author ");
String author = input.nextLine();
System.out.print("Please enter the year: ");
String year = input.nextLine();
System.out.print("Please enter the page count: ");
String pageCount = input.nextLine();
System.out.print("Please enter the genre: ");
String genre = input.nextLine();
bookClass book = new bookClass(title, author, year, pageCount, genre);
books1DArray[0] = book.getTitle();
books1DArray[1] = book.getAuthor();
books1DArray[2] = book.getYear();
books1DArray[3] = book.getPageCount();
books1DArray[4] = book.getGenre();
}
for (String[] books1DArray: books2DArray) {
printSummary( books1DArray[0], books1DArray[1], books1DArray[2], books1DArray[3], books1DArray[4]);
}
System.out.println("There are" + book.getBookCount() + "books in the system");
}
public static void printSummary(String title, String author, String year, String pageCount, String genre) {
System.out.format("%s written by %s was published in %s, has %s pages and is of the %s genre", title, author, year, pageCount, genre);
}
}
I have multiple issues/questions:
Would it be better to create the array in the main class?
I feel like I am being highly inefficient as it feels like I am repeating myself in the code over and over. Some of the redundancy is necessary for good practice (such as getters and setters), but am I overdoing it?
In the for loop in the main class, I want to create multiple objects and add them to the array, but I am unsure how to do that as it would require different names to avoid being overwritten.
Also, calling getBookCount at the end of my main class does not work. Is there a reason for this?
I would appreciate any general advice or other things you may notice, as I feel as though I am fundamentally misunderstanding the use of Java classes.
You are learning Java, so you should learn Java name conventions.
I assume your book class public class BookClass, you can write your test class that uses 1 array of BookClass (or ArrayList or any collection type you want), for example (Skip input checking)
public class BookTest {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("How many books would you like to enter: ");
int bookAmount = input.nextInt(); input.nextLine();
BookClass[] books = new BookClass[bookAmount];
for (int i = 0; i < bookAmount; i++) {
System.out.print("Please enter the title: ");
String title = input.nextLine();
System.out.print("Please enter the author ");
String author = input.nextLine();
System.out.print("Please enter the year: ");
String year = input.nextLine();
System.out.print("Please enter the page count: ");
String pageCount = input.nextLine();
System.out.print("Please enter the genre: ");
String genre = input.nextLine();
books[i] = new BookClass(title, author, year, pageCount, genre);
}
for (BookClass book : books) {
printSummary(book.getTitle(), book.getAuthor(), book.getYear(), book.getPageCount(), book.getGenre());
}
System.out.println("There are" + books.length + "books in the system");
}
public static void printSummary(String title, String author, String year, String pageCount, String genre) {
System.out.format("%s written by %s was published in %s, has %s pages and is of the %s genre", title, author, year, pageCount, genre);
}
}
You don't need static attribute in BookClass to store the number of books, you have many ways to do it.
Your getBookCount does not work because you call an undefined parameter book which you defined in side for loop. If you want, you should define a static getter method public static int getBookCount(), and access it BookClass.getBookCount(). But I advice you to do not use it to count object, because it can make wrong in complicated program when you remove object, use multi-threading with out synchronization ...

Not sure how to create an object with Java Scanner and storing it inside an ArrayList

I'm currently trying to make an Object with Java Scanner input.
This object CashCard contains the fields amount, name & amountcardisused.
But i'm not sure how i can get inputs from java Scanner and than move it inside my ArrayList CashCard.
This is mycode so far, i'm not sure how to continue, hopefully you can help me out.
Class Cashcard
package cashcard;
import java.util.ArrayList;
public class CashCard {
private double amount;
private String name;
private int amountcardisused;
private ArrayList<CashCard> listofcashcards;
public CashCard(String name, double amount, int amountcardisused){
this.amount = amount;
this.name = name;
this.amountcardisused = amountcardisused;
listofcashcards = new ArrayList<CashCard>();
}
public String setName(String name){
return name;
}
public double setAmount(double amount){
return amount;
}
public int setTimesCardIsUsed(int amountcardisused){
return amountcardisused;
}
}
Class TestCashCard
package cashcard;
import java.util.*;
public class TestCashCard {
ArrayList<CashCard> listofcashcards = new ArrayList<CashCard>();
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String input;
// Stop console when entering 0 in console
System.out.println("0: Stop Program");
System.out.println("1: Add CashCard");
// Execute this code when entering 1 in console
System.out.println();
System.out.print("Enter 0 or 1: ");
input = in.nextLine();
if(input.equals("0")){
System.exit(0);
}
else if(input.equals("1")){
System.out.print("Enter name of the card owner: ");
String yourname = in.nextLine();
System.out.println("Enter the amount you want to set on your cashcard: ");
double youramount = in.nextDouble();
System.out.print("Enter The Amount This Card Is Already Used: ");
int youramountcardisused = in.nextInt();
// Do Something to create an CashCard object by using the scanner its input
// and than put the object inside the ArrayList CashCard.
// Need help on this part
}
else{
System.out.print("No choice is made, close program");
System.exit(0);
}
}
}
Your CashCard shouldn't contain an ArrayList of CashCard objects. You can remove that and keep your ArrayList in your main class.
So you could do this in your main:
ArrayList<CashCard> myCashCards = new ArrayList<CashCard>();
//Scanner input here.
CashCard cashCard = new CashCard(yourname, youramount, youramountcardisused);
myCashCards.add(cashCard);
Only thing you have to do is
public CashCard(String name, double amount, int amountcardisused){
this.amount = amount;
this.name = name;
this.amountcardisused = amountcardisused;
//remove the below line from here
listofcashcards = new ArrayList<CashCard>();// dont include this here
}
and in your testcashcard class
after
System.out.print("Enter The Amount This Card Is Already Used: ");
int youramountcardisused = in.nextInt();
add
CashCard cashcard1 = new CashCard("abc",1000,2);
listofcashcards.add(cashcard1);
If your desire is to keep a list of all created CashCards inside your CashCard class (rather than your test class), make your ArrayList field static, like so:
private double amount;
private String name;
private int amountcardisused;
// change your line below to this
private static ArrayList<CashCard> listofcashcards = new ArrayList<CashCard>();
Write two access methods for your ArrayList field (again in your CashCard class):
public static void addCashCard(CashCard cc) {
listofcashcards.add(cc);
}
public static ArrayList<CashCard> getAllCashCards() {
// Return new list copied from field (for field protection)
return new ArrayList<CashCard>(listofcashcards);
}
Then, when you want to add a new card using your test class, use your constructor and the addCashCard method to store the new card in your shared field:
...
System.out.print("Enter The Amount This Card Is Already Used: ");
int youramountcardisused = in.nextInt();
// Create your object using the constructor, and add it to your list,
// which lives inside your CashCard class
CashCard.addCashCard(new CashCard(yourname, youramount, youramountcardisused));
...
Voila! If you want to access all your cards from your test class simply call CashCard.getAllCashCards()

my input array keeps over writing itself

Every time i pass an object to my array, it overwrites the previous entry. Can anybody spot why this is happening?
addbook() - when i put in name, and author it assigns a value , but when enter another title and author, it overwrites the previous entry.
public class library {
static Scanner keyboard = new Scanner(System.in);
static int count = 0;
public static void main(String [] args){
addBook();
} // Main end
static void addBook(){
loanbook [] loanArray = new loanbook[5];
String title,author;
int choice;
boolean onLoan;
loanbook book1; // TESTING ONLY
for(int x = 0; x < 5; x++){
System.out.print("Press 1 for Fiction or 2 for Non Fiction: "); // sub menu for fiction and non fiction
choice = keyboard.nextInt();
if (choice == 1){
System.out.println("Please enter book title: ");
title = keyboard.nextLine();
title = keyboard.nextLine();
System.out.println("Please enter book author: ");
author = keyboard.nextLine();
onLoan = false; // not used yet
book1 = new fiction(title,author);
System.out.println(book1.toString());
loanArray[x] = new loanbook(title,author);
}
else if (choice == 2) {
System.out.println("Please enter book title: ");
title = keyboard.nextLine();
title = keyboard.nextLine();
System.out.println("Please enter book author: ");
author = keyboard.nextLine();
onLoan = false; // not used yet
book1 = new nonfiction(title,author);
System.out.println(book1.toString());
loanArray[x] = new loanbook(title,author);
}
}
}
} // Library end
My Loanbook class
public class loanbook {
private String title,author;
private int bookID, count = 0;
public loanbook(String pTitle,String pAuthor){
bookID = count;
title = pTitle;
author = pAuthor;
count++;
} // Constructor
public void setTitle(String pTitle){
title = pTitle;
} // setTitle
protected String getTitle(){
return title;
} // getTitle
protected String getAuthor(){
return author;
} // getAuthor
public String toString(){
return " BookID: "+ bookID+"\n" + " Title: "+ getTitle()+"\n" +" Author : "+ getAuthor()+ "\n";
}
} // loanbook
You may want to make count static. I'm assuming you want the count to go up every time a new book is created. Without the static, the count value will not persist ever time a book is created, so your bookID will always be 0 for every book. That may be why you think "it's getting overwriten". I'm not totally sure because you haven't really explained what that means.
private int bookID;
public static int count = 0; <-- static
public loanbook(String pTitle,String pAuthor){
bookID = count;
title = pTitle;
author = pAuthor;
count++;
}
Or better yet, just avoid the count variable. You do the same as you would with the count. So count is unnecessary.
public static int bookID 0;
public loanbook(String pTitle,String pAuthor){
title = pTitle;
author = pAuthor;
bookId++;
}
Also, I don't know what you're planning to with loanbook book1;, but it is used every time in the loop, so I could see this being the possible "it is getting overwritten" problem. Assuming fiction and nonfiction extend loanbook
Also I don't see a need for the count in the library class. You can get rid of that.
Update:
Assuming you want the fiction or nonfiction book (and they both extend loanbook) in yourloanArray` may you want something like this
loanbook book = new fiction(title,author);
System.out.println(book1.toString());
loanArray[x] = book;

No Such Element Exception for Book Store Kiosk

So this is a rough work in progress. I am making a text based information kiosk where people can do a search by author, title, etc. Right now I am having a hard time adding book using the kiosk. I can add all the info, but after I enter the information per book, I get a No Such Element exception. No sure what that means and any help would be appreciated.
import java.util.Scanner;
import java.util.ArrayList;
public class Books{
public static void main(String[] args) {
//Part 1: Initialize the MIS
//Part 1.1: Open Scanner
Scanner keyboard = new Scanner(System.in);
//Part 1.2: Build a store
Store newstore = new Store();
//Part 1.3: Build an array of books
final int MAX_NUM_BOOKS = 500;
Books[] list_book = new Books[MAX_NUM_BOOKS];
//Part 1.4: Prompt for the initial book count
System.out.println("How many books do we have?");
int bookcount = keyboard.nextInt();
//Part 1.5: Builds the books
for(int i=0; i<bookcount; i++) list_book[i] = new Books();
//Part 1.6: Create switch menu
boolean exit = false;
while(!exit){
System.out.println("Please make a selection: ");
System.out.println("To search by Title (0)");
System.out.println("To search by Author's Last name (1)");
System.out.println("To search by Author's First name (2)");
System.out.println("To search by ISBN (3)");
System.out.println("To add a book to the inventory (4)");
System.out.println("To exit (5)");
int option = keyboard.nextInt();
switch(option){
case 0:System.out.print("Please enter the title of the book you are looking for: ");
String title = keyboard.next();
results(Book.TitleSearch(title));
break;
case 1: System.out.print("Please enter the last name of the author you are looking for: ");
String auth_last = keyboard.next();
results(Book.Auth_LastSearch(auth_last));
break;
case 2:System.out.print("Please enter the first name of the author you are looking for: ");
String auth_first = keyboard.next();
results(Book.Auth_FirstSearch(auth_first));
break;
case 3:System.out.print("Please enter the ISBN of the book you are looking for: ");
String ISBN = keyboard.next();
results(Book.ISBNSearch(ISBN));
break;
case 4:addBook(newstore);
break;
case 5: exit=true;
}//switch
}//while
//Part :Close Input
keyboard.close();
}
//Part 2: Add Books to the Store
private static void addBook(Store newstore) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter title of the book: ");
String title = keyboard.next();
System.out.print("Enter Author's first name: ");
String auth_first_nam = keyboard.next();
System.out.print("Enter Author's last name: ");
String auth_last_nam = keyboard.next();
System.out.print("Enter the ISBN: ");
String isbn = keyboard.next();
Book book = new Book(title, auth_first_nam, auth_last_nam, isbn);
Store.addBook(book);
keyboard.close();
}
private static String results(String titleSearch) {
return Book.output();
}
}
//Build each individual book
class Book{
private static String title;
private static String auth_first_nam;
private static String auth_last_nam;
private static String isbn;
private static String bookinfo;
public Book(Scanner keyboard){
System.out.println("Enter the book Title: ");
title=keyboard.next();
System.out.println("Enter in the Author's Last Name: ");
auth_last_nam=keyboard.next();
System.out.println("Enter in the Author's First Name: ");
auth_first_nam=keyboard.next();
System.out.println("Enter the ISBN number: ");
isbn=keyboard.next();
}
public Book(String title, String auth_first_nam, String auth_last_nam, String isbn) {
}
public static String output() {
bookinfo=(title+" by " + auth_first_nam + " " + auth_last_nam + ". ISBN: " +isbn);
return bookinfo;
}
public static String ISBNSearch(String iSBN2) {
return isbn;
}
public static String Auth_FirstSearch(String auth_first) {
return auth_first_nam;
}
public static String Auth_LastSearch(String auth_last) {
return auth_last_nam;
}
public static String TitleSearch(String title2) {
return title;
}
public String getTitle() {
return title;
}
public String GetAuthorLast(){
return auth_last_nam;
}
public String GetAuthorFirst(){
return auth_last_nam;
}
public String getISBN() {
return isbn;
}
}
class Store{
private static ArrayList<Book> books;
private static Book book;
public Store(){
books = new ArrayList<Book>();
}
public static void addBook(Book Book){
if(book==null){
System.out.println("I'm sorry, but you didn't enter in any information.");
return;
}
else{
books.add(Book);
}
}
public Book getTitle(String title){
for(int i=0;i<books.size(); i++)
{
if(books.get(i).getTitle().equals(title))
{
book=books.get(i);
}
}
return book;
}
public ArrayList<Book> findAutLast(String aut_last_nam)
{
ArrayList<Book> found = new ArrayList<Book>();
for(int i=0; i<books.size(); i++)
{
Book current = books.get(i);
if(current.GetAuthorLast().indexOf(aut_last_nam) >=0)
{
found.add(current);
}
}
return found;
}
public ArrayList<Book> findTitle(String title){
ArrayList<Book> found = new ArrayList<Book>();
for(int i=0; i<books.size();i++)
{
Book current = books.get(i);
if (current.getTitle().indexOf(title) >=0)
{
found.add(current);
}
}
return found;
}
public ArrayList<Book> findISBN(String isbn)
{
ArrayList<Book> found = new ArrayList<Book>();
for(int i=0; i<books.size(); i++)
{
Book current = books.get(i);
if(current.getISBN().indexOf(isbn) >=0)
{
found.add(current);
}
}
return found;
}
}
Sorry, there's some dead code and loose ends still being tied up. Just really curious about the No Element as I've never seen it before. It happens at line 35 after using the Switch for case 4.
The issue is actually in this method:
private static void addBook(Store newstore) {
...
keyboard.close();
}
Where you close the keyboard instance of a Scanner.
The loop in which you call addBook is making use of the keyboard scanner, and the next time through the loop calls keyboard.nextInt() fails, because the scanner is closed.
I deduced this by running your code, and observing the following exception:
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:838)
at java.util.Scanner.next(Scanner.java:1461)
at java.util.Scanner.nextInt(Scanner.java:2091)
at java.util.Scanner.nextInt(Scanner.java:2050)
at Books.main(Books.java:36)
Notably, line 36 is
int option = keyboard.nextInt();
And I only hit this exception after running option 4 (add a book).
If you remove keyboard.close() from your addBook() method, your program will no longer crash.
I don't expect your program to work, as you have a number of other errors (misuse of static fields and methods), but it will no longer throw a NoSuchElementException.
As a hint (since this appears to be homework), the other problems I'm seeing in your program:
static fields for Book (so the properties you wish to define on a book won't persist with the object)
static method son Book (similar to above)
failure to set fields in Book using the appropriate constructor (and repeating code from addBook in an inappropriate constructor)
Creating a Books[] instead of what you likely want, which is a Book[] (or maybe this is irrelvant since you have an ArrayList<Book> books in Store
Though it's really hard to tell because you haven't provided the stacktrace, I could see a problem arrising when to access an element in the ArrayList. It's hard to tell just by staring at your code, but I would start by fixing this
private static String title;
private static String auth_first_nam;
private static String auth_last_nam;
private static String isbn;
private static String bookinfo;
All of these fields you have as static. That means that for every Book you create and add the ArrayList of books, every single one will have the exact same title, auth_first_nan, auth_last_nam, isbn, and bookinfo. That could cause a problem in the program. Though probably doesn't cause the NoSuchElementException, I would still make this fix.
For example, if you first add a Book with title "StackOverflow", then you add a Book with title "StackExchange", the first Book's title also become "StackExchange". That means that if you ever try and access a Book by title "StackOverflow", you would never find it
Change all the fields to not include the static
private String title;
private String auth_first_nam;
private String auth_last_nam;
private String isbn;
private String bookinfo;
Check out Java tutorial for static keyword

Categories