my input array keeps over writing itself - java

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;

Related

How do I create a class designated to store an array, and then call it from any other method?

I am trying to clean my code up by creating a class specifically for an array of information. It is basically like a storage for variables in case I need them later. Here is what I have so far:
package com.input;
import java.util.Scanner;
public class Gender extends Welcome {
Scanner input = new Scanner(System.in);
private static String gender;
public static void setGender() {
Scanner input = new Scanner(System.in);
int[] storeInts = new int[25];
storeInts[0] = 0;
//The [0] index of array storeInformation is the gender value. 0 = female; 1 = male
gender = input.nextLine();
if(gender.equalsIgnoreCase("boy")) {
System.out.println("What is your name, sir?");
while (storeInts[0] < 1) {
storeInts[0]++;
}
}else if(gender.equalsIgnoreCase("girl")) {
System.out.println("What is your name, ma'am?");
}else{
System.out.println("You have failed to answer correctly. Try again:");
init();
}
Name nameObject = new Name();
nameObject.setName(storeInts[0]);
}
public static void nextName(int x) {
if(x == 1) {
System.out.println("What is your name, sir?");
}else{
System.out.println("What is your name, ma'am?");
}
Name nameObject = new Name();
nameObject.setName2();
}
}
What I'm trying to accomplish here, is if the user types "boy" my code will store 1 in the index [0] of array storeInts[]. If the user types "girl" the index [0] will remain the value of 0.
If I need to refer to the user's gender later on, I want to be able to go back and figure out if they are a "boy" or a "girl" using the array.
I want to be able to called this array from any method within my code. I have already used this array in a complicated way and I would like to find a solution to make it easier.
Here is when I used it:
nameObject.setName(storeInts[0]);
I transferred the index [0] to the setName() method.
Here is the setName() method:
public void setName(int x) {
String name;
name = input.nextLine();
String storedStrings[] = new String[25];
storedStrings[0] = name;
FirstTask firstTaskObject = new FirstTask();
if (name.length() == 0) {
System.out.println("You must be a unicorn. You want to play games?");
altInit(x);
}else{
System.out.println("Nice to meet you, " + name + "!");
firstTaskObject.beginning(name);
}
}
As you can see I created another array in the same manner as the previous one, but this one is to store Strings instead. Now back to what I was saying-- the parameter (int x) is the same value as storeInts[0]. This will tell me if the user is male or female. This value is sent to altInit() method when the user decides to try to continue without typing their name in first.
Here is the altInit() method:
public void altInit(int x) {
String yesOrNo;
AltStory altStoryObject = new AltStory();
Gender backToGender = new Gender();
yesOrNo = input.nextLine();
if(yesOrNo.equalsIgnoreCase("yes")) {
altStoryObject.AltInit();
}else if(yesOrNo.equalsIgnoreCase("no")) {
System.out.println("Consider this your last warning...");
backToGender.nextName(x);
}else{
System.out.println("You have failed to answer correctly. Try again:");
init();
}
}
When asked if they want to play games, they can type "yes" or "no." If the user types "no" as in they do not want to play games, then the program will print, "Consider this your last warning..." and then continue to the nextName() method in the previous class Gender. This also passes on that index[0] again in the array storedInts[].
Here is the nextName() method:
public static void nextName(int x) {
if(x == 1) {
System.out.println("What is your name, sir?");
}else{
System.out.println("What is your name, ma'am?");
}
Name nameObject = new Name();
nameObject.setName2();
}
As you can see, if the user is that value of a male (or 1) then the program will print, "What is your name, sir?." If the value is a female (or 0), then the program will print, "What is your name, ma'am?"
This whole time I felt like the stored value of storeInts[0], was just leap frogging around until it was used... I want to prevent this by just creating a class with methods giving me the ability to call any value stored in that array whenever I need it. How do I create an array, store it in a method, and call it when needed?
As someone has requested, here is the entire code:
//Gender class
package com.input;
import java.util.Scanner;
public class Gender extends Welcome {
Scanner input = new Scanner(System.in);
private static String gender;
public void setGender() {
Scanner input = new Scanner(System.in);
int [] storeInts = new int[25];
storeInts[0] = 0;
//The [0] index of array storeInformation is the gender value. 0 = female; 1 = male
gender = input.nextLine();
if (gender.equalsIgnoreCase("boy")) {
System.out.println("What is your name, sir?");
while(storeInts[0]<1){
storeInts[0]++;
}
} else if (gender.equalsIgnoreCase("girl")) {
System.out.println("What is your name, ma'am?");
} else {
System.out.println("You have failed to answer correctly. Try again:");
init();
}
Name nameObject = new Name();
nameObject.setName(storeInts[0]);
}
public void nextName(int x){
if (x == 1) {
System.out.println("What is your name, sir?");
}else {
System.out.println("What is your name, ma'am?");
}
Name nameObject = new Name();
nameObject.setName2();
}
}
//Name class
package com.input;
public class Name extends Gender{
public void setName(int x) {
String name;
name = input.nextLine();
String storedStrings[] = new String[25];
storedStrings[0] = name;
FirstTask firstTaskObject = new FirstTask();
if (name.length() == 0) {
System.out.println("You must be a unicorn. You want to play games?");
altInit(x);
} else {
System.out.println("Nice to meet you, " + name + "!");
firstTaskObject.beginning(name);
}
}
public void altInit(int x){
String yesOrNo;
AltStory altStoryObject = new AltStory();
Gender backToGender = new Gender();
yesOrNo = input.nextLine();
if(yesOrNo.equalsIgnoreCase("yes")) {
altStoryObject.AltInit();
}else if(yesOrNo.equalsIgnoreCase("no")){
System.out.println("Consider this your last warning...");
backToGender.nextName(x);
}else{
System.out.println("You have failed to answer correctly. Try again:");
init();
}
}
public void setName2() {
String name;
name = input.nextLine();
FirstTask firstTaskObject = new FirstTask();
if (name.length() == 0) {
System.out.println("You have failed to answer correctly. Try again:");
init();
} else {
System.out.println("Nice to meet you, " + name + "!");
firstTaskObject.beginning(name);
}
}
}
How do I create an array, store it in a method, and call it when needed?

How can i use a constructor using JOptionPane to pass objects from my method into a empty array?

I'm having trouble figuring out how to store the objects from the constructor. so far all I get is one object and the remaining are all null. If someone can explain it to me so that a beginner can understand that would be much appreciated.
public class Bookstore
{
/*
Main Class Bookstore to be made modular
*/
public static void main(String args[])
{
Book catalogue[] = new Book[3];
int select;
do
{
select = bookMenu();
switch(select)
{
case 1:
int i =0;
if(catalogue[i] != null)
{
JOptionPane.showMessageDialog(null,"Test");
break;
}
catalogue[i] = addBook();
case 2:
sortBook();
break;
case 3:
searchBook(catalogue);
break;
case 4:
displayBook(catalogue);
break;
case 5:
break;
}
}
while(select != 5);
}
public static int bookMenu()
{
int select;
String menuOptions = "--Book store--\n"
+ "\n1. Add book to catalogue"
+ "\n2.Sort and display books by price"
+ "\n3. Search for a book by title"
+ "\n4. Display all books"
+ "\n\n5. Exit";
do
{
select = Integer.parseInt(JOptionPane.showInputDialog(menuOptions));
}
while(select < 1 || select > 5);
return select;
}
public static Book addBook()
{
int isbn;
String title, author;
Book catalogue = null;
double price;
for(int i=0; i<3;i++)
{
isbn = Integer.parseInt(JOptionPane.showInputDialog
("Enter Book ISBN or: "));
title = JOptionPane.showInputDialog
("Enter Book Title: ");
author = JOptionPane.showInputDialog
("Enter Book Author: ");
price = Double.parseDouble(JOptionPane.showInputDialog
("Enter Book Price: "));
catalogue = new Book(isbn, title, author, price);
}
return catalogue;
}
public static void sortBook()
{
}
public static void searchBook(Book catalogue[])//remain void
{
String searchValue = JOptionPane.showInputDialog("Enter the title of the book you are searching for");
boolean found = true;
for(int i=0; i<catalogue.length && catalogue[i] != null ; i++)
{
if(searchValue.equalsIgnoreCase(catalogue[i].getTitle()))
{
JOptionPane.showMessageDialog(null, "Book details: " + catalogue[i].toString());
found = true;
}
}
if(found == false)
JOptionPane.showMessageDialog(null, "The title does not exist in the collection ");
}
public static void displayBook(Book catalogue[])//remain void
{
String output = "";
for(Book bk:catalogue)
{
output += bk + "\n";
}
JOptionPane.showMessageDialog(null, output);
}
}
So, this is always false...
if(count == max)
You set the values immediately before that statement. Zero never equals ten.
Some IDEs would even point that out to you.
If you want to get a variable that can be used between methods, you need to learn variable scoping.
For example, using a static class variable
private static Book[] books;
private static final int MAX_BOOKS = 10;
private static int count;
public static void main(String[] args) {
books = getBooks();
bookMenu();
}
public static Book[] getBooks() {
if(count == MAX_BOOKS) {
JOptionPane.showMessageDialog(null, "Catalogue full - cannot add any more books");
} else {
for(; count < MAX_BOOKS; count++) {
books[count]= addBook();
}
}
return books;
}
Then, if you want to repeat the menu, use a loop. Don't place it at the end of every method.
Also searchBook(Book) isn't searching for a title. You want to pass a string to the method, not a Book class

JAVA So i have this code that i am using arrays of [60] and when i use the add command it rewrites all the previous statements i made

Could you please help me figure out why when i add a new book it overwrites all of the books with the current one? ---------------------- |Name| -|ISBN|-|Author|
for example i add a book called |game| | of | Thrones|
and if i go & add a book named |Song| | of | Ice and fire |
no matter if there are 10 books there they will all be renamed according to the last entry
(here Song of ice and fire)
//Package ask1 main class Library
package ask1;
import java.lang.Object.*;
import java.util.Scanner;
import java.util.Arrays;
import java.io.*;
public class library {
public static void main(String[] args) throws InstantiationException, IllegalAccessException {
Management manager = new Management();
Scanner input = new Scanner(System.in);
Book vivlio = new Book();
System.out.println("\n\t\t^*^*^*^*^*^*^* LIBRARY MANAGEMENT ^*^*^*^*^*^*^");
while (true) {
System.out.println("------------------MENU-------------------------------");
System.out.print("\nENTER UR CHOICE\n\t" +
"1:Add a new Book\n\t" +
"2:Edit Book Infos\n\t" +
"3:Search a Book (with ISBN)\n\t" +
"4:Show all the Books\n\t" +
"5:Delete a Book (with ISBN)\n\t" +
"6:Exit \n :");
int selection;
selection = input.nextInt();
if (selection == 1) {
System.out.println("Adding a new book ");
String empty = input.nextLine();
System.out.println("name of book:");
vivlio.name = input.nextLine();
System.out.println("Author:");
vivlio.author = input.nextLine();
System.out.println("ISBN:");
vivlio.isbn = input.nextLine();
System.out.println("Number of copies:");
vivlio.number = input.nextInt();
System.out.println("");
manager.AddBook(vivlio);
} else if (selection == 2) {
System.out.println("Editing a Book ");
System.out.println("Please enter title of book to edit:");
String title = input.next();
Book editingBook = findBookByTitle(title);
if (editingBook == null) {
System.out.println("Sorry no book found with title name = " + title);
} else {
//ask user for new price etc what ever you want to edit.
System.out.println("Please enter new values:");
String newValue = input.nextLine();
editingBook.setPrice(newValue);
// etc. other editing to book.
}
} else if (selection == 3) {
System.out.println("Searching a Book ");
} else if (selection == 4) {
System.out.println("You Choose to view all the Books ");
manager.PrintAllBooks();
} else if (selection == 5) {
System.out.println("You Choose to Delete a Book ");
String empty = input.nextLine();
} else if (selection == 6) {
System.out.println("Library System Terminated!!! ");
String empty = input.nextLine();
System.exit(0);
} else {
System.out.println("Wrong Choice");
}
}
}
private static Book findBookByTitle(String title) {
// TODO Auto-generated method stub
return null;
}
here is the second class called Book
package ask1;
import java.util.Scanner;
public class Book {
Scanner input = new Scanner(System.in);
public String isbn;
public String name;
public String author;
public int number;
public String getIsbn() {
return isbn;
}
public void setIsbn(String isbn) {
this.isbn = isbn;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
String bookinfo = name + " ," + author + " ," + isbn;
public void setPrice(String newPrice) {
// TODO Auto-generated method stub
}
}
And the third class called Management
package ask1;
import java.util.Scanner;
public class Management {
Scanner input = new Scanner( System.in );
private Book[] books =new Book [60];
private String isbns = new Book().isbn;
private String name = new Book().name;
int current = 0;
//Number 1
public void AddBook(Book vivlio)
{
books[current]=vivlio;
current++;
}
//Number 3
//Number 4
public void PrintAllBooks()
{
for (int i=0;i<current;i++)
{
Book b = books[i];
System.out.println(b.name);
}
}
}
return searchBook;
}
}
The problem is that vivlio always means the same book. You only create one Book object, here:
Book vivlio = new Book();
and proceed to add it to the list several times, while changing its name each time. However, since it's just one book that happens to be on the list several times, when you change one you change all.
You can make it better by simply changing the scope. Move the creation of the book inside the loop:
while(true) {
Book vivlio = new Book();
...
Now vivlio is initialized to a different book each time, instead of using the same book all the time.
Your problem: You create Book vivlio = new Book(); once and re-use it every time. So whenever you set a parameter, you set it for this one book and therefore overwrite what you did before.
The easiest solution is to move
Book vivlio = new Book();
into your while loop.
That will create a new Book object each time you run through the loop.
By the way, there would be some ways to improve the code. For example, don't reference another object's attribute directly, but use getter and setter methods. Also, it is pretty standard to start function names with lower case chars.
Book object is created only once and after calling the following method.
public void AddBook(Book vivlio) {
books[current] = vivlio;
current++;
}
You are just assigning the same object object to array.
That means you are changing the values inside vivlio again and again but referencing the same object in array to different places thats why you are getting the same output in all the books.
Here is the right code for your reference.
public class library {
public static void main(String[] args) throws InstantiationException,
IllegalAccessException {
Management manager = new Management();
Scanner input = new Scanner(System.in);
System.out
.println("\n\t\t^*^*^*^*^*^*^* LIBRARY MANAGEMENT ^*^*^*^*^*^*^");
while (true) {
Book vivlio = new Book();
System.out
.println("------------------MENU-------------------------------");
System.out
.print("\nENTER UR CHOICE\n\t1:Add a new Book\n \t2:Edit Book Infos\n\t3:Search a Book (with ISBN)\n\t4:Show all the Books\n\t5:Delete a Book (with ISBN)\n\t6:Exit \n :");
int selection;
selection = input.nextInt();
if (selection == 1) {
System.out.println("Adding a new book ");
String empty = input.nextLine();
System.out.println("name of book:");
vivlio.name = input.nextLine();
System.out.println("Author:");
vivlio.author = input.nextLine();
System.out.println("ISBN:");
vivlio.isbn = input.nextLine();
System.out.println("Number of copies:");
vivlio.number = input.nextInt();
System.out.println("");
manager.AddBook(vivlio);
}
else if (selection == 2) {
System.out.println("Editing a Book ");
System.out.println("Please enter title of book to edit:");
String title = input.next();
Book editingBook = findBookByTitle(title);
if (editingBook == null) {
System.out.println("Sorry no book found with title name = "
+ title);
} else {
// ask user for new price etc what ever you want to edit.
System.out.println("Please enter new values:");
String newValue = input.nextLine();
editingBook.setPrice(newValue);
// etc. other editing to book.
}
}
else if (selection == 3) {
System.out.println("Searching a Book ");
} else if (selection == 4) {
System.out.println("You Choose to view all the Books ");
manager.PrintAllBooks();
} else if (selection == 5) {
System.out.println("You Choose to Delete a Book ");
String empty = input.nextLine();
} else if (selection == 6) {
System.out.println("Library System Terminated!!! ");
String empty = input.nextLine();
System.exit(0);
} else {
System.out.println("Wrong Choice");
}
}
}
private static Book findBookByTitle(String title) {
// TODO Auto-generated method stub
return null;
}
}
Hope this might solve your problem.

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

getting elements to stick in an array in java (mock bookstore project)

new to java here. Having trouble with multiple parts of this project to make a mock bookstore. where i'm at right now is correctly getting new books to stick in the books[] array past the first one i put in. when i run methods "listTitles" and "listBooks" in the bookstore class, it only show me the first book that i'ved logged. in addition to that i'm having trouble implementing two other methods: the "addNewBook" method and the "sellBook" method also in the bookstore class. if your on this page, please let me know what i'm doing/not doing to get those methods to work. you'll see commented code for the intended parameters of each method. sorry if its a bit of a mess, Thanks for your time.
Class: MyBookStore
public class MyBookstore {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
Bookstore mybookstore = new Bookstore();
int user_choice;
do {
System.out.println();
System.out.println("1) Add a book to the stock");
System.out.println("2) Sell a book in stock");
System.out.println("3) List the titles of all the books in stock");
System.out.println("4) List all the information about the books in stock");
System.out.println("5) Print out the gross income of the bookstore");
System.out.println("6) Quit");
System.out.println();
System.out.print("please select one of the six options");
System.out.println();
System.out.print("your choice:");
user_choice = s.nextInt();
switch (user_choice) {
case 1:
System.out.println("Enter a title");
String title = s.next();
System.out.println("how many pages is the book?");
int pages = s.nextInt();
System.out.println("how much does this book cost?");
double price = s.nextInt();
System.out.println("how many of these books are there in stock?");
int stock = s.nextInt();
Book c = new Book(title, pages, price, stock);
mybookstore.addNewBook(c);
break;
case 2:
System.out.println("Selling books:");
System.out.println("Enter the title...");
String an = s.next();
System.out.println("Enter a quantity");
int da = s.nextInt();
mybookstore.sellBook(an, da);
break;
case 3:
mybookstore.listTitles();
break;
case 4:
mybookstore.listBooks();
break;
case 5:
mybookstore.getIncome();
break;
default:
System.out.println("please select from one of the six options");
}
} while (user_choice != '6');
}
}
Class: Bookstore
class Bookstore {
private Book[] books; // all the books in this bookstore
private int totalBooks; // the number of books in this bookstore
private double grossIncome; //the gross income of the bookstore (will be incremented when books are sold)
public Bookstore() {
books = new Book[100];
totalBooks = 0;
grossIncome = 0;
}
//If it is already in stock, simply ask the user to enter how many extra books to stock, and then do so.
public void addNewBook(Book b) {
books[totalBooks] = b;
totalBooks++;
for (int i = 0; i < totalBooks; i++) {
if (b.getTitle() == books[i].getTitle()) {
String name = b.getTitle();
Scanner m = new Scanner(System.in);
System.out.println("books is already in stock, how many additonal books would you like to stock?");
int stock = m.nextInt();
addBookQuantity(name, stock);
}
}
System.out.println("book has been logged");
return;
}
public void addBookQuantity(String title, int quantity){
// Adds quantity number of books to the book already in stock in the Bookstore object with
// the title title. If the book is not in the Bookstore object, nothing is done.
for (int i =0; i<totalBooks; i++) {
if (title == books[i].getTitle()) {
books[i].addQuantity(quantity);
System.out.println("quantity added successfully");
return;
}
}
System.out.println("book not found.");
}
// Returns true if quantity or more copies of a book with the title title are contained in the Bookstore object.
public boolean inStock(String title, int quantity){
for (int i =0; i<totalBooks; i++) {
if (title == books[i].getTitle()) {
if (quantity <= books[i].getQuantity()) {return true;}
else {return false;}
}
}
return false;
}
// Executes selling quantity number of books from the Bookstore object with the title title to the
// buyer. The Bookstore object is changed to reflect the sale. The gross income of the bookstore is incremented
//accordingly. The method returns true is the sale was executed successfully, false otherwise.
public boolean sellBook(String title, int quantity){
for ( int i = 0; i < totalBooks;) {
if (title == books[i].getTitle() ) {
books[i].subtractQuantity(quantity);
double l = books[i].getPrice();
double profit = l*quantity;
grossIncome = grossIncome + profit;
//rework this
System.out.println("books sold. Total store profits:" + profit);
}
}
return false;//System.out.println("Book not in stock");
}
public void listTitles(){
// Lists all of the titles of the books in the Bookstore object.
for (int i = 0; i<totalBooks; ) {
System.out.println(books[i].getTitle());
return;
}
}
// Lists all of the information about the books in the Bookstore object.
public void listBooks(){
for (int i = 0; i<totalBooks;) {
System.out.println(books[i].toString());
return;
}
}
// Returns the total gross income of the Bookstore object.
public double getIncome(){
return grossIncome;
}
}
Class: Book
class Book {
private String title;
private int numOfPages;
private double price;
private int quantity;
public Book(String theTitle, int pages, double cost, int num) {
title = theTitle;
numOfPages = pages;
price = cost;
num = quantity;
}
public String getTitle() {
return title;
}
public double getPrice() {
return price;
}
public int getQuantity() {
return quantity;
}
public String toString() {
return "Title:" + title + "\nNumber of pages: " + numOfPages + "\nPrice:" + price + "\nquantity left:" + getQuantity();
}
public void subtractQuantity(int amount) {
quantity = quantity - amount;
}
}
private Book[] books; // all the books in this bookstore
private int totalBooks;
This is a double administration, and if not all books are getting listed, my bet is that totalBooks = 1 but books.length is > 1.
The quickest solution would be to drop totalBooks and to use books.length everywhere.
Aside from that I'd recommend you use an ArrayList instead to store the books.
public void listTitles(){
// Lists all of the titles of the books in the Bookstore object.
for (int i = 0; i<totalBooks; ) {
System.out.println(books[i].getTitle());
return;
}
}
Should be:
public void listTitles(){
// Lists all of the titles of the books in the Bookstore object.
for (int i = 0; i<totalBooks; i++) {
System.out.println(books[i].getTitle());
}
return;
}
The reason it only shows the first one is because the way you have your code currently the loop would only execute once and then hit the return statement. return means "return to main" essentially so the loop in this case is useless.
I moved your return statement out of the loop and added the "i++" to your loop. It should work fine now.
Of course as others have suggested, ArrayList may be better suited for this but I'm assuming you're trying to learn Java so its better you stick with what you've picked for now and understand where you're making mistakes. Fixing your mistakes is the best way to learn.
Do keep ArrayLists in mind for later though.
-------------------------Regarding a question in the comments below--------------------
As I said I still haven't had the time to look at it and test it but here's a clue I can offer so you can work on your methods:
public void addNewBook(Book b){
books[totalBooks] = b;
totalBooks ++;
for (int i =0; i<totalBooks; i++) {
if ( b.getTitle() == books[i].getTitle()) {
String name = b.getTitle();
Scanner m = new Scanner(System.in);
System.out.println("books is already in stock, how many additonal books would you like to stock?");
int stock = m.nextInt();
addBookQuantity(name, stock);
}
}
System.out.println("book has been logged");
return;
}
Your method above starts off by adding books to your array. You might want to change the method thusly:
public void addNewBook(Book b) {
if (books.length != 0) {
// check if the title is already added
for (int i = 0; i < books.length; i++) {
if (books[i].getTitle().equals(b.getTitle())
// dont add book title again
else
// add book title
}
} else {
// add book title
}
}
As flup already suggested though you could use a Set and then convert the Set back to an array. Sets only store unique values and Java has a method for sets that will convert it to an array.

Categories