The original BookOrder class did not have any methods, or variables, to handle dates(I'm working out of Murach's "Beginning
Java 2"). The assignment was to add these things, including the "Date: " + date + "\n\n" line to the toString() method. The resulting code is almost exactly like the example given in the book, yet when the main class calls toString(), all the lines after the "Date: " + date + "\n\n" line runs.
I've tried running the debugger to see what is happening, but Sun ONE locks up whenever I run it.
This is driving me nuts, because I don't think the code is wrong. Any help is appreciated.
//BOOKORDER CLASS
import java.util.*;
import java.text.*;
public class BookOrder{
private Book book;
private int quantity;
private double total;
private
String date;
public BookOrder(String bookCode, int bookQuantity){
book = new Book(bookCode);
quantity = bookQuantity;
setTotal();
setDate();
}
public void setTotal(){
total = quantity * book.getPrice();
}
public void setDate()
{
// Get current date.
GregorianCalendar gregDate = new GregorianCalendar();
// Convert to millisecond form.
Date now = gregDate.getTime();
// Create a date format.
DateFormat dtfDate = DateFormat.getDateInstance(DateFormat.SHORT);
// Assign date format to string.
date = dtfDate.format(now);
}//end setDate()
public String getDate()
{
return (date);
}//end getDate()
public Book getBook(){
return book;
}
public int getQuantity(){
return quantity;
}
public double getTotal(){
return total;
}
// "Date: " + date + "\n\n" does not display.
public String toString(){
NumberFormat currency = NumberFormat.getCurrencyInstance();
String orderString = "Date: " + date + "\n\n"
+ "Code: " + book.getCode() + "\n"
+ "Title: " + book.getTitle() + "\n"
+ "Price: " + currency.format(book.getPrice()) + "\n"
+ "Quantity: " + quantity + "\n"
+ "Total: " + currency.format(total) + "\n";
return orderString;
}
}
MAIN CLASS
import javax.swing.JOptionPane;
public class BookOrderApp{
public static void main(String[] args){
String choice = "";
try{
while (!(choice.equalsIgnoreCase("x"))){
String title = JOptionPane.showInputDialog(
"Enter a book code:");
String inputQuantity = JOptionPane.showInputDialog(
"Enter a quantity:");
int quantity = parseQuantity(inputQuantity);
BookOrder bookOrder = new BookOrder(title, quantity);
String message = bookOrder.toString() + "\n"
+ "Press Enter to continue or enter 'x' to exit:";
choice = JOptionPane.showInputDialog(null,
message, "Book Order", JOptionPane.PLAIN_MESSAGE);
}//end while
}
catch(NullPointerException e){
System.exit(0);
}
System.exit(0);
}
public static int parseQuantity(String quantityString){
int quantity = 0;
boolean tryAgain = true;
while(tryAgain){
try{
quantity = Integer.parseInt(quantityString);
tryAgain = false;
}
catch(NumberFormatException e){
quantityString = JOptionPane.showInputDialog(null,
"Invalid quantity. \n"
+ "Please enter an integer.");
}
}
return quantity;
}
}