に負の値を処理の問題が生じています、私はdiscount.javaとTestDiscount.javaというクラスを書いています。これまでのすべてが動作しますが、実際の値の代わりにエラーメッセージを表示するのに問題があります。ここで必要な出力と私がこれまで行っているについて少し詳細情報は以下のとおりです。Imはdiscount.javaというクラスを書いて、私が述べたように、私は量と価格
出力は形式である必要があります。
量は次のとおりです。単価はあるXX:$ XX.XX割引です:$ XX.XX
それとも
量は次のとおりです。-XX数量がマイナスです。 $ 15.00お金負である、ことはできません 計算割引額
public class discount {
int quantity;
double price;
public static int NINETY_NINE = 99;
public static int TWENTY = 20;
private static int TEN = 10, FORTY_NINE = 49;
public static double TEN_PERCENT = 0.10, FIVE_PERCENT = 0.05,
TWO_PERCENT = 0.02, THREE_PERCENT = 0.03, ONE_PERCENT = 0.01 ;
private double discount;
// public static double discount_amount = discount * quantity * price;
discount(int quantity, double price)
{
double discount = 0;
//double d = discount;
this.quantity = quantity;
this.price = price;
}
boolean quantityOutOfRange()
{
return quantity < 0;
}
boolean priceOutOfRange()
{
return price < 0;
}
public double getDiscount()
{
return discount;
}
public int getQuantity()
{
return quantity;
}
public double getUnitPrice()
{
return price;
}
public void calculate()
{
if (quantity > NINETY_NINE)
{
if (price > TWENTY)
discount = TEN_PERCENT;
else if (price > TEN)
discount = FIVE_PERCENT;
else
discount = TWO_PERCENT;
}
else if (quantity > FORTY_NINE)
{
// calculate discount
if (price > TWENTY)
discount = THREE_PERCENT;
else if (price > TEN)
discount = TWO_PERCENT;
else
discount = ONE_PERCENT;
}
else
{
// calculate discount
if (price > TWENTY)
discount = TWO_PERCENT;
else if (price > TEN)
discount = ONE_PERCENT;
else
discount = 1;
}
if (quantity < 0)
{
System.out.println("Quantity is negative. Cannot compute discount");
}
//double discount_amount = discount * quantity * price;
}
}
public class TestDiscount {
public static void main(String[] arg) {
String input = JOptionPane.showInputDialog("Enter the quantity desired "
+ ", and unit price "
+ "\n(Separated by spaces)");
Scanner in = new Scanner(input);
int quantity = in.nextInt();
double price = in.nextDouble();
discount current = new discount(quantity, price);
current.calculate();
System.out.println("\nDiscounts:\n");
System.out.println("The quantity is: " + current.getQuantity()+ "\tThe unit price is = $ " + current.getUnitPrice() +
"\tThe discount is = $ " + current.getQuantity()* current.getUnitPrice() * current.getDiscount());
System.exit(0) ;
}
}
ヒントのための最初のチェック計算:クラス名は大文字で始まります。もちろん、これは学習に過ぎませんが、実際のアプリケーションでは、money/currencyを表すためにfloat/doubleのプリミティブ型を使用しないでください。もう一つは、中かっこなしのif/then/elseを避けてください。 1つのステートメントだけがあっても、いつでも 'if(whatever){statement}'を実行することができます。あなたは、エラーが発生したことを「捕獲」し、それに有用な何かを行うことはできません: 'System.out'を使用して、エラーメッセージ、' System.err'などをプリントアウトすることは多くの使用でないことを – GhostCat
注意。例外(例えば 'IllegalArgumentException')を投げる方が良い方法です。 –
定数のヒント:定数NINETY_NINEはちょうどそれはまだ「マジックナンバー」である99を使用するよりも良くない、そしてそれが変更されたとき、あなたはまだどこにでもそれを変更する必要があります - あなたは以外にNINETY_NINEを再定義する場合を除き、 99、それははるかに悪化するでしょう。数値*が何を意味するのかを表す定数、つまりMAX_QUANTITY、またはDISCOUNT_THRESHOLDを使用します。すべてのヒントについては、そんなに –