我的代碼:爲什麼價格打印兩次?
package ecommerceapp;
import java.util.Scanner;
public class ECommerceApp {
public static void main(String[] args) {
String productsCatalog = " ";
//double price = getPrice();
bannerPrinter();
productsBuilder();
boolean exists = getOrder(productsCatalog);
if (exists == true) {
double salesTotal = 0;
printTotal(salesTotal);
} else {
System.out.println("The product not found.");
}
//double price = 0;
//double tax = getTax(price);
//getTotal(price, tax);
}
public static void bannerPrinter() {
System.out.println("******************************************");
System.out.println("====== Welcome to my eCommerce app! ======");
System.out.println("******************************************");
}
public static String productsBuilder() {
String productsCatalog = "Desk Table Pen ";
return productsCatalog;
}
public static boolean getOrder(String productsCatalog) {
String userProduct;
boolean exists = true;
Scanner scnr = new Scanner(System.in);
System.out.print("Please enter a product name: ");
userProduct = scnr.nextLine();
if (productsBuilder().toLowerCase().contains(userProduct.toLowerCase())) {
exists = true;
System.out.println(exists);
} else {
exists = false;
System.out.println(exists);
}
return exists;
}
public static double getPrice() {
double price = 1 + Math.random() * 99;
price = Math.round(price * 100.0)/100.0;
System.out.println("Price is: " + price);
return price;
}
public static double getTax(double price) {
double tax = (0.1 * getPrice());
tax = Math.round(tax * 100.0)/100.0;
System.out.println("Tax is: " + tax);
return tax;
}
public static double getTotal(double price, double tax) {
double salesTotal = getPrice() + getTax(price);
return salesTotal;
}
public static void printTotal(double salesTotal) {
double price = 0;
double tax = 0;
System.out.printf("Your sale total is: $%.2f", getTotal(price, tax));
System.out.println();
}
}
爲什麼我的輸出打印價格的兩倍?
======歡迎來到我的電子商務應用! ======
請輸入產品名稱:辦公桌
真正
價格爲:64.43
價格爲:85.07
稅爲:8.51
您的銷售總額爲:$ 72.94
生成成功(總時間:3秒)
當我從兩個用getPrice和getTax除去的System.out.println,這是我的輸出
======歡迎到我電子商務應用程序! ======
請輸入產品名稱:辦公桌
真正
稅:8.6
你的銷售總額爲:$ 38.60
沒有getter方法打印任何東西。他們應該返回一個值,並沒有副作用。 –
我的提交將不會顯示價格或稅金,但我希望價格僅生成一次,無論如何。 – Sharon
你的代碼有太多的問題恕我直言,恕我直言。底線是你打電話兩次,這是打印兩次。你的許多方法返回你永遠不會使用的值。 –