import javax.swing.JOptionPane;
import java.text.DecimalFormat;
public class CandleLine
{
public static void main(String[] args)
{
double dollars, answer;
int shipmentCode;
dollars = getPrice();
shipmentCode = getCode();
answer = getTotalPrice(dollars,shipmentCode);
output(answer,dollars);
finish();
}
public static double getPrice()
{
double price = 0.0;
boolean done = false;
while (!done)
{
String answer = JOptionPane.showInputDia开发者_JAVA百科log(null,"Enter the original price\n(do not use commas or dollar signs)\n or click Cancel to exit:");
if (answer == null) finish();
try
{
price = Double.parseDouble(answer);
if (price <= 0) throw new NumberFormatException();
else done = true;
}
catch(NumberFormatException e)
{
JOptionPane.showMessageDialog(null,"Your entry was not in the proper format.","Error",JOptionPane.INFORMATION_MESSAGE);
}
}
return price;
}
public static int getCode()
{
int code = 0;
boolean done = false;
while (!done)
{
try
{
String message = "Enter the shipment code:" + "\n\n1) Priority\n2) Express\n3) Standard\n\n";
code = Integer.parseInt(JOptionPane.showInputDialog(null,message));
if (code<1 || code>3) throw new NumberFormatException();
else done = true;
}
catch(NumberFormatException e)
{
JOptionPane.showMessageDialog(null,"Please enter a 1, 2, or 3.","Error",JOptionPane.INFORMATION_MESSAGE);
}
}
return code;
}
public static double getTotalPrice(double price, int shipmentcode)
{
double totalprice = 0.0;
switch(shipmentcode)
{
case 1:
totalprice = 14.95 + price;
break;
case 2:
totalprice = 11.95 + price;
break;
case 3:
totalprice = 5.95 + price;
break;
}
return totalprice;
}
public static void output(double totalprice, double price)
{
DecimalFormat twoDigits = new DecimalFormat("$#.00");
JOptionPane.showMessageDialog(null,"Your shipment fee is" + shipmentcode,"Shipment Fee",JOptionPane.INFORMATION_MESSAGE);
JOptionPane.showMessageDialog(null,"Your total cost is" + twoDigits.format(totalprice),"Price Total",JOptionPane.INFORMATION_MESSAGE);
}
public static void finish()
{
System.exit(0);
}
}
. . . . . . . . . The case 3 needs to be zero when it total price exceeds $75 (no shipping cost over that price). How do I implement this?
case 3:
if (price > 75 ) {
totalPrice = price;
} else {
totalprice = 5.95 + price;
}
break;
So in total, how many possibilities are there for the shipping cost of an order?
final double [] shipmentprice = {14.95, 11.95, 5.95};
public static double getTotalPrice (final double price, final int shipmentcode)
{
return price + shipmentprice[shipmentcode -1];
}
A shorter code, but not very object oriented. I'm not sure whether I see an Enum rising. :)
精彩评论