Hi,
I'm doing self-study from Murach's Beginning
Java 2.
My exercise is to convert an application to object-oriented application. "Start a new class named Invoice and save it to .... Then, write the code for this class so it provides all of the data operations related to an Invoice object. Its constructor should require the order total as its only paranters, and it should initialize instance variables for order totals, discount amount, and invoice total. One of it's methods shold be the toString method, which returns a
string that contains all of the data for an invoice. As you work you may want to move code from the InvoiceApp class to the Invoice class. Modify the code in the InvoiceApp class so it creates and uses Invoice objects."
I'm really stuck on the toString method. In my Invoice.java I get errors about being able to resolve orderTotal, discountAmount, and invoiceTotal. Not to say that the rest of Invoice.java is close to being right, but that's where I'm getting the errors.
FWIW this is in Chapter 4 and a few of the things that the chapter is trying to teach are : creating objects, constructors, methods, calling methods, static fields and methods.
import javax.swing.*;
public class EnhancedInvoiceApp
{
public static void main(String[] args)
{
try
{
String choice = "";
while (!(choice.equalsIgnoreCase("x"))) // begin while loop
{
String inputString = JOptionPane.showInputDialog(
"Enter order total: ");
double orderTotal = Double.parseDouble(inputString);
double discountAmount = 0;
if (orderTotal >= 100)
discountAmount = orderTotal * .2;
else
discountAmount = orderTotal * .1;
double invoiceTotal = orderTotal - discountAmount;
String message = "Order total: " + orderTotal + "\n"
+ "Discount amount: " + discountAmount + "\n"
+ "Invoice total: " + invoiceTotal + "\n\n"
+ "To continue, press Enter.\n"
+ "To exit, enter 'x': ";
choice = JOptionPane.showInputDialog(message);
} // end while loop
}
catch(NullPointerException e)
{
System.exit(0);
}
}
}
----------------------------------
public class Invoice
{
private String message;
public Invoice(double orderTotal)
{
double discountAmount;
double invoiceTotal;
if (orderTotal >= 100)
discountAmount = orderTotal * .2;
else
discountAmount = orderTotal * .1;
invoiceTotal = orderTotal - discountAmount;
}
public String toString()
{
String message = "Order total: " + orderTotal + "\n"
+ "Discount amount: " + discountAmount + "\n"
+ "Invoice total: " + invoiceTotal + "\n\n"
+ "To continue, press Enter.\n"
+ "To exit, enter 'x': ";
return message;
}
}