Need lots of help getting a class/driver program to work
I am writing a program for a book store that prompts a user to enter the information about the book they are buying. I am having multiple problems, but one is that I cannot get the proper input from the user. When someone selects to buy a book, they should be able to enter the title, isbn, price, and author individually, but for some reason its not wokring.
Also, if they choose to list the books in their cart, I can't get the variable numberOfBooks. I'm not sure how to get it. If you can, please take a look at the code and give me some pointers. Thank you all!
Book class file
// ***************************************************************************
// Title: Book.java
// Description: Class program for basic book information
//
// Assumptions:
//
// Deficiencies: See ShoppingCart
//
// ***************************************************************************
// ***************************************************************************
// REQUIRED PACKAGES
// ***************************************************************************
publicclass Book{
// ***************************************************************************
// INSTANCE VARIABLES
// ***************************************************************************
private String bookTitle,
bookAuthor,
bookIsbn;// class invariant: 10 character limit
privatedouble bookPrice;
// ***************************************************************************
// CONSTRUCTORS
// ***************************************************************************
/* Default constructor */
public Book(){
this("booktitle",
"bookauthor",
"bookisbn",
0.0);
}
/* Comprehensive constructor */
public Book(String bookTitle,
String bookAuthor,
String bookIsbn,
double bookPrice){
setBookTitle(bookTitle);
setBookAuthor(bookAuthor);
setBookIsbn(bookIsbn);
setBookPrice(bookPrice);
}
// ***************************************************************************
// MUTATOR METHODS
// ***************************************************************************
publicvoid setBookTitle(String bookTitle){
this.bookTitle = bookTitle;
}
publicvoid setBookAuthor(String bookAuthor){
this.bookAuthor = bookAuthor;
}
publicvoid setBookIsbn(String bookIsbn){
this.bookIsbn = bookIsbn;
}
publicvoid setBookPrice(double bookPrice){
this.bookPrice = bookPrice;
}
// ***************************************************************************
// ACCESSOR METHODS
// ***************************************************************************
public String getBookTitle(){
return bookTitle;
}
public String getBookAuthor(){
return bookAuthor;
}
public String getBookIsbn(){
return bookIsbn;
}
publicdouble getBookPrice(){
return bookPrice;
}
// ***************************************************************************
// PUBLIC INTERFACE METHODS
// ***************************************************************************
// Precondition:
// Postcondition:
publicboolean equals(Book book){
if (this.bookTitle == book.bookTitle &&
this.bookAuthor == book.bookAuthor &&
this.bookIsbn == book.bookIsbn &&
this.bookPrice == book.bookPrice)
returntrue;
else
returnfalse;
}
// Precondition: Book object has been instantiated
// Postcondition: returns Sting representing current state of object
public String toString(){
return"Title: " + bookTitle +"\nAuthor: " +
bookAuthor +"\nISBN: " + bookIsbn +"\nPrice: " +
bookPrice;
}
// ***************************************************************************
// PRIVATE HELPER METHODS
// ***************************************************************************
// Precondition: requires a string to be tested and an integer value
//representing a particular type of test for string length:
//(1) - maximum length of 10
// Postcondition: returns "true" if string length = particular maximum length
privateboolean checkBookLength(String string,
int typeOfTest){
int properLength = 10;
switch (typeOfTest){
case 1:
properLength = 10;
break;
default:
System.out.println("Improper value for \"typeOfTest\" variable");
}
if (string.length() == properLength)
returntrue;
else
returnfalse;
}
private String bookIsbnLength()
{
if (bookIsbn.length() == 10){
this.bookIsbn = bookIsbn;
}
else{
System.out.println("Book ISBN must be 10-digits.");
System.exit(1);
}
return bookIsbn;
}
}
ShoppingCart (Driver Program)
// ****************************************************************************
// Title: ShoppingCart.java
//
// Description: Driver for testing Book class.
//
// Assumptions: None
//
// Deficiencies: -Doesn't store the values of the book correctly
//-Doesn't clear the cart correctly (exits instead)
//-Doesn't check the ISBN 10 digit values
//
// ****************************************************************************
import java.util.Scanner;
publicclass ShoppingCart{
privatestatic Scanner keyboard =new Scanner(System.in);
publicstaticvoid main(String[] args){
int numberOfBooks;
//Book myBook = new Book();
Book[] myBook =new Book[5];
do{
displayMenu();
switch(readInput()){
case 1:
System.out.print("How many books are you buying?");
numberOfBooks = keyboard.nextInt();
for(int i=0; i< numberOfBooks; i++){
myBook[i] =new Book();
System.out.print("Enter Authors Name ");
myBook[i].setBookAuthor(keyboard.nextLine());
System.out.print("Enter ISBN # ");
myBook[i].setBookIsbn(keyboard.nextLine());
System.out.print("Enter Price ");
myBook[i].setBookPrice(keyboard.nextDouble());
}
break;
case 2:
numberOfBooks = keyboard.nextInt();
for(int i=0; i<numberOfBooks; i++){
System.out.print(myBook[i]);
}
break;
case 3:
numberOfBooks = keyboard.nextInt();
for (int i=0; i><numberOfBooks; i++){
myBook[i] =new Book();
}
case 4:
System.exit(0);
break;
default:
System.out.println("Wrong Choice!");
}
}while(true);
}
privatestaticvoid displayMenu(){
System.out.println(" 1 - Add a book to the shopping cart");
System.out.println(" 2 - List books in shopping cart");
System.out.println(" 3 - Clear shopping cart");
System.out.println(" 4 - Exit");
}
privatestaticint readInput(){
int menuChoice = keyboard.nextInt();
if (menuChoice == 1 || menuChoice == 2 || menuChoice == 3 || menuChoice == 4){
returnmenuChoice;
}else{
return 0;
}
}
}
>
[14325 byte] By [
eristica] at [2007-11-27 7:57:01]

> but for some reason its not wokring.
You need to provide more details. Do you go to the doctor and say "I'm sick" and expect him to cure you?
In your readInput method:
int menuChoice = keyboard.nextInt();
keyboard.nextLine(); // add this line
I have found several careless errors.
1) rather than array of books, I'd use an ArrayList<Book>. It's more flexible and allows for easier adding and removal of books.
2) This:
case 2:
numberOfBooks = keyboard.nextInt(); //? WTF ?
for (int i = 0; i < numberOfBooks; i++)
{
System.out.print(myBook[i]);
}
break;
doesn't make any sense.
3) This:
case 3:
numberOfBooks = keyboard.nextInt(); //? WTF ?
for (int i = 0; i < numberOfBooks; i++)
{
myBook[i] = new Book();
}
also doesn't make any sense. Also, where's your "break;" statement here?
I'm sure there's more
try now
import java.util.Scanner;
public class ShoppingCart {
private static Scanner keyboard = new Scanner(System.in);
public static void main(String[] args) {
keyboard.useDelimiter(System.getProperty("line.separator"));
int numberOfBooks=0;
//Book myBook = new Book();
Book[] myBook = new Book[5];
do {
displayMenu();
switch(readInput()) {
case 1:
//int i=0;
System.out.print("How many books are you buying?");
numberOfBooks = keyboard.nextInt();
for(int i=0; i<numberOfBooks; i++) {
myBook[i] = new Book();
System.out.print("Enter Authors Name ");
String author = keyboard.next();
myBook[i].setBookAuthor(author);
System.out.print("Enter ISBN # ");
String isbn = keyboard.next();
myBook[i].setBookIsbn(isbn);
System.out.print("Enter Price ");
double price = keyboard.nextDouble();
myBook[i].setBookPrice(price);
}
break;
case 2:
// numberOfBooks = keyboard.nextInt();
System.out.println();
for( int i=0; i><numberOfBooks; i++) {
System.out.print(myBook[i]);
}
break;
case 3:
//numberOfBooks = keyboard.nextInt();
for (int i=0; i><numberOfBooks; i++) {
myBook[i] = new Book();
}
case 4:
System.exit(0);
break;
default:
System.out.println("Wrong Choice!");
}
} while(true);
}
private static void displayMenu() {
System.out.println(" 1 - Add a book to the shopping cart");
System.out.println(" 2 - List books in shopping cart");
System.out.println(" 3 - Clear shopping cart");
System.out.println(" 4 - Exit");
}
private static int readInput() {
int menuChoice = keyboard.nextInt();
if (menuChoice == 1 || menuChoice == 2 || menuChoice == 3 || menuChoice == 4) {
returnmenuChoice;
} else {
return 0;
}
}
}
option 1 and 2 are working fine. have;nt gone for option 3 and 4. Good luck. Like pete said ArrayList are the best>
Okay... I guess I should take this 1 problem at a time. I can't get the program to compile because of option 2.
case 2:
// numberOfBooks = keyboard.nextInt();
System.out.println();
for( int i=0; i><numberOfBooks; i++) {
System.out.print(myBook[i]);
}
break;
I tried to look at your code lrngjava but what is i><numberOfBooks?
I wrote it just as i >< numberOfBooks but now it says that numberOfBooks isn't initialized. How do I retrieve the numberOfBooks value from case 1 ? I want option 2 to reprint how many books there are in the shopping cart. Also, we haven't learned array lists yet, so I have no idea how to go about using those.
Message was edited by:
eristic
no thats the forum problem for(int i=0; i<numberOfBooks; i++)forums will replace all >< to ><
1) >< is a forum error. I didn't read that post, but it is either > or < or >= or <=
2) regarding numberOfBooks: get rid of it. You don't want to know the number of books, trust me, you want to use an ArrayList and just keep accepting book entries until the user is done.
Is an array list very complicated to learn? We have not been taught array lists yet.
ArrayLists are very easy to learn. They are basically a dynamic array. You can add as many items to an ArrayList as you like, whereas arrays have a size limit.
I'm not really sure how to set the data of the book to the array list. I made this so far:
ArrayList books = new ArrayList;
I found a site that has an example to add stuff into an array manually in the code, but I don't know how to add stuff to it, when the user is inputting. Before I used an array but not sure how to do this with the arraylist
ArrayList is a class. What is missing from your code? You need this evertime you create an object.Look in the API for ArrayList. It will list the methods it has available.
int numberOfBooks;
ArrayList books = new ArrayList();
case 1:
System.out.print("How many books are you buying?");
numberOfBooks = keyboard.nextInt();
books(numberOfBooks);
Eclipse says "this method book(int) is undefined for the type ShoppingCart"
What am I doing wrong, I just want to add the capacity
http://java.sun.com/j2se/1.4.2/docs/api/java/util/ArrayList.html#add(int,%20java.lang.Object)
edit: books.add(numberOfBooks) ?
Message was edited by:
eristic
You don't add the capacity to your ArrayList, you add books. If you need to specify the capacity then use the constructor that accepts an int.
This is what I have so far... So i don't add to the array, I add books? But don't I need to store the books into the array? How do I do that without adding to the array list?
int numberOfBooks;
ArrayList books = new ArrayList();
Book myBook = new Book();
do {
displayMenu();
switch(readInput()) {
case 1:
System.out.print("How many books are you buying?");
numberOfBooks = keyboard.nextInt();
books.add(numberOfBooks);
for(int i=0; i< numberOfBooks; i++) {
//myBook[i] = new Book();
System.out.print("Enter Title ");
String title = keyboard.next();
books.setBookTitle(title);
System.out.print("Enter Authors Name ");
String author = keyboard.next();
myBook[i].setBookAuthor(author);
System.out.print("Enter ISBN # ");
String isbn = keyboard.next();
myBook[i].setBookIsbn(isbn);
System.out.print("Enter Price ");
Double price = keyboard.nextDouble();
myBook[i].setBookPrice(price);
}
break;
> But don't I need to store the books into the array? How do I do that without adding to the array list?Please re-read my previous reply.
Okay, could you suggest anything ?
case 1:
System.out.print("How many books are you buying?");
numberOfBooks = keyboard.nextInt();
//books.add(numberOfBooks);
for(int i=0; i< numberOfBooks; i++) {
//myBook[i] = new Book();
System.out.print("Enter Title ");
String title = keyboard.next();
myBook.setBookTitle(title);
System.out.print("Enter Authors Name ");
String author = keyboard.next();
myBook.setBookAuthor(author);
System.out.print("Enter ISBN # ");
String isbn = keyboard.next();
myBook.setBookIsbn(isbn);
System.out.print("Enter Price ");
Double price = keyboard.nextDouble();
myBook.setBookPrice(price);
books.add(myBook);
}
Well I could suggest something. How about having a nice chicken and avocado roll for lunch.
Do you have a specific question?
ok serious advice. Use a constructor instead of all those setter methods.
books.add(new Book(title, author, isbn, price));
Ok. That helped. I didn't really understand what you meant by use a constructor until you posted that. I was thinking about the default and comprehensive constructor.Message was edited by: eristic
I tried this:
System.out.println("Enter Title ");
String title = keyboard.next();
books.add(0 new Book(title));
but it said that the constructor Book(String) was undefined so, I think maybe it has to be first? Now does this constructor need a default and comprehensive constructor as well? Also, would it need to be put in my Book class file (as opposed to the current ShoppingCart) ?
Message was edited by:
eristic
books.add(0 new Book(title));Surely you should be able to see the difference between your code and my example.
honestly, it looks identical. You see, I'm very new to java and it is very hard for me.
C'mon! You're new, not blind. Please tell me that this:books.add(new Book(title, author, isbn, price));doesn't look like this:books.add(0 new Book(title));
The reason I did it as
books.add(0 new Book(title));
was because since i'm prompting the user for 1 thing at a time, I thought that I had to "trim" that to each statement... ie:
when prompted for the author then it would read
books.add(0 new Book(author));
or when prompted for isbn
books.add(0 new Book(price));
When I put the full statement at the end of case 1, eclipse said that the statement is never read, that's why I split it up, but obviously that didn't work. I'm posting less frequently because I'm trying to get it to work before posting again. I don't want to bug too too much.
> The reason I did it as
> books.add(0 new Book(title));
>
>
> was because since i'm prompting the user for 1 thing
> at a time, I thought that I had to "trim" that to
> each statement...
Obviously, that's not how this works. And obviously it is different from the example. Even you can see that, correct?
> I'm posting less frequently because I'm trying to
> get it to work before posting again. I don't want
> to bug too too much.
Good. Keep at it.
If you do it that way you will put an object in the ArrayList wirh only a title and no other info. You then replace that object with a new object that has an author and no other info. The you replace that object with a new object etc etc.
Get all your info first and then do as my code example. You will create one object which contains all the correct info.
Can I get all the info while still prompting the user for one piece at a time? Or do I have to prompt the user to enter everything at once?
Have a look at your original code (several posts up). It gets all the info one bit at a time. So instead of having all those setter methods calls, you delete them. Then at the end once you have read in all the info you create your object and add it to the ArrayList. Just needs you to exercise the grey matter a little.
I see what you mean. I thought that since I wasn't immediately saving them, the program would throw away the values or forget about them. That's why I kept splitting it up (the arraylist line)Message was edited by: eristic
Values stored in variables are only discarded when you overwrite them with a new value or when the program exits the block in which the variable was declared, at which time the variable itself becomes unreachable.
would i use a mutator to check to see if the isbn of the book is 10 characters long? I've been testing it, and since there is no setter method in there to grab snippets of the information that is entered, it just prints the following no matter what:
public void setIsbn(String isbn) {
if (isbn.length() == 10) {
this.isbn = isbn;
} else System.out.print("ISBN must be 10 characters long.\n");
}
This is a design decision you will have to make. One option is to do the check when you read in the isbn. If the user has enetered an invalid value, inform them and get them to enter in a valid one before proceding. Therefore when you create a new Book object it can only receive a valid number.
Ok. I'll do that when its entered, if , else.
Now, how do I control the output of the arraylist. Well, not the output, but the formatting of it. I have attached a screenshot for you to see that it needs a few \n after the price and ISBN, but I am clueless as to how I go about doing that since I cannot "see" the formatting of the arraylist data until I print it.
http://i53.photobucket.com/albums/g56/learntobndg/ShoppingCart.png
Your book method overrides toString(). This is good and should format things for you. The only thing left to do is to iterate through the ArrayList which is done similar to iterating through an array:
for (int i = 0; i < myArrayList.size(); i++)
{
System.out.println(myArrayList.get(i));
}
I see what you meant about the toString. Since I am extending my book class from my Items class, (since I have a CD class as well that extends Items), I had to add the \n , because it was using return super.toString, then appending what I added from the book class.
For some reason still, when the ISBN is 10 digits long, it prints "the ISBN must be 10 digits long" and when it isn't, and you select print your values, it displays "null"
public void setIsbn(String isbn) {
if (isbn.length() == 10) {
this.isbn = isbn;
} else System.out.print("ISBN must be 10 characters long.\n");
}
I'm not sure how to fix this. Maybe I can just add an if isbn.length() != 10, then "yell at user"and put that in the ShoppingCart file and remove this mutator?
EDIT:
I can't take it out because my comprehensive contructor needs the mutator to set the ISBN. Not sure how to fix it. I believe I wrote the comparison correctly, if it == 10 then set it, else yell at user. What am I doing wrong?
Message was edited by:
eristic
> I can't take it out because my comprehensive
> contructor needs the mutator to set the ISBN. Not
> sure how to fix it. I believe I wrote the comparison
> correctly, if it == 10 then set it, else yell at
> user. What am I doing wrong?
You may be "yelling at the user", but are you allowing them to fix the error?
I have sometimes used a while loop in this situation. For instance:
public static void wtf()
{
Scanner keyboard = new Scanner(System.in);
int foo = 3;
while (foo != 7)
{
System.out.print("Enter an integer (seven prefered): ");
while (!keyboard.hasNextInt())
{
keyboard.nextLine(); // if input not an integer, swallow it.
}
foo = keyboard.nextInt();
keyboard.nextLine();
if (foo != 7)
{
System.out.println("Hey idiot! I said that seven was preferred!!!");
}
else
{
System.out.println("Good for you. You selected 7.");
}
}
}
Message was edited by:
petes1234
I'm almost there, I just need to get it out of the while loop once its true.
> I'm almost there, I just need to get it out of the> while loop once its true.then that's your while condition -- that it's not true. Once it is true, it automatically falls out of the loop.
public void setIsbn(String isbn) {
while (isbn.length() != 10) {
System.out.println("Enter an ISBN of length 10");
isbn = keyboard.next();
if (isbn.length() != 10) {
System.out.println("ISBN MUST BE OF LENGTH 10!!");
}
else {
System.out.println("ISBN entered correctly");
this.isbn = isbn;
}
}
}
That's what I thought, but it's not "seeing" the latest isbn.lenth() value. I think I might need to move the last line of this.isbn=isbn out one set of squiggly brackets.
Don't you meanOnce it is false, it automatically falls out of the loop.I'm going insaneMessage was edited by: flounder
> That's what I thought, but it's not "seeing" the
> latest isbn.lenth() value. I think I might need to
> move the last line of this.isbn=isbn out one set of
> squiggly brackets.
It's not "seeing" the isbn because you're not putting it into the variable if it doesn't have length 10. But it doesn't really matter as long as the isbn was properly initialized to some value of length not equal to 10. Proper initialization of variables is key.
Message was edited by:
petes1234
I hate getting stuck on such trivial things.Here is what I'm working with now
public void setIsbn(String isbn) {
int isbnLength = isbn.length();
while (isbnLength != 10) {
System.out.print("Enter an ISBN 10 characters long: ");
isbn = keyboard.next();
if (isbn.length() != 10) {
System.out.println("ISBN MUST BE 10 characters long!!!");
}
else {
System.out.println("ISBN entered correctly\n");
isbnLength = 10;
this.isbn = isbn;
}
}
}
OUTPUT:
Enter Title math
Enter Authors Name einstein
Enter ISBN # 123
Enter Price 314
Enter an ISBN 10 characters long: 12345678
ISBN MUST BE 10 characters long!!!
Enter an ISBN 10 characters long: 1234567890
ISBN entered correctly
Enter an ISBN 10 characters long: 1234567890
ISBN entered correctly
1 - Add a book to the shopping cart
2 - Add a CD to the shopping cart
3 - List items in shopping cart
4 - Clear shopping cart
5 - Exit
Message was edited by:
eristic
1) The variable isbnLength adds nothing. I strongly recommend that you get rid of it.
2) If you look at the output, you will see that the problem doesn't lie in your setIsbn method, but it's in the method that's calling it. Study that more closely and you'll find your error (it is surely calling the setIsbn method multiple times).
Ya I just tested it. I took out the above code and put my original yell at user but no chance to fix it, and it still outpust twice.
How many books are you buying? 1
Enter Title math
Enter Authors Name einstein
Enter ISBN # 123
Enter Price 314
ISBN must be 10 characters long.
ISBN must be 10 characters long.
I'm going to look around tomorrow. I think it has something to do with the toString from my Items class (since Book extends from Items class). But, Items doesn't have isbn in its toString, so maybe its somewhere else. I'll have to look around some more. I'll post some more tomorrow night. Thanks for all the help.
EDIT: Ok. Almost positive its something in teh Book class. Maybe the comprehensive constructor ?
import java.util.Scanner;
***************************************************************************
// REQUIRED PACKAGES
// ***************************************************************************
public class Book extends Item {
// ***************************************************************************
// INSTANCE VARIABLES
// ***************************************************************************
private String isbn; // class invariant: 10 character limit
// ***************************************************************************
// CONSTRUCTORS
// ***************************************************************************
/* Default constructor */
public Book() {
this("title",
"author",
"isbn",
0.0);
}
/* Comprehensive constructor */
public Book(String title,
String author,
String isbn,
Double price) {
setTitle(title);
setAuthor(author);
setIsbn(isbn);
setPrice(price);
}
// ***************************************************************************
// MUTATOR METHODS
// ***************************************************************************
private static Scanner keyboard = new Scanner(System.in);
public void setIsbn(String isbn) {
if (isbn.length() == 10) {
this.isbn = isbn;
} else System.out.print("ISBN must be 10 characters long.\n");
}
/**
public void setIsbn(String isbn) {
while (isbn.length() != 10) {
System.out.print("Enter an ISBN 10 characters long: ");
isbn = keyboard.next();
if (isbn.length() != 10) {
System.out.println("ISBN MUST BE 10 characters long!!!");
}
else {
System.out.println("ISBN entered correctly\n");
this.isbn = isbn;
}
}
}
*/
// ***************************************************************************
// ACCESSOR METHODS
// ***************************************************************************
public String getIsbn() {
return isbn;
}
// ***************************************************************************
// PUBLIC INTERFACE METHODS
// ***************************************************************************
// Precondition:
// Postcondition:
public String toString() {
return super.toString() +
"\nISBN: " + isbn + "\n";
}
public boolean equals(Book book) {
if (this.isbn == book.isbn)
return true;
else
return false;
}
// ***************************************************************************
// PRIVATE HELPER METHODS
// ***************************************************************************
// Precondition: requires a string to be tested and an integer value
//representing a particular type of test for string length:
// Postcondition: returns "true" if string length = particular maximum length
}
Message was edited by:
eristic
Personally, I wouldn't check the isbn input in the constructor but before calling the constructor. I'd get the input, make sure it was correct, and only then stuff it into the constructor.