我的代码:
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();
}
}
为什么我的输出打印两次价格?
======欢迎使用我的电子商务应用! ==
请输入产品名称:desk
真
价格是:64.43
价格是:85.07
税收是:8.51
您的销售总额为:72.94美元
建立成功(总时间:3秒)
当我从getPrice和getTax中删除System.out.println时,这是我的输出
======欢迎使用我的电子商务应用! ==
请输入产品名称:desk
真
税收是:8.6
您的销售总额为:$ 38.60
答案 0 :(得分:5)
因为您正在打印getPrice的结果。并且getPrice本身就是打印价格,因此,您的程序打印价格两次。删除getPrice块中的“System.out.println”函数。
答案 1 :(得分:3)
因为您在getPrice()
和getTax()
中拨打getTotal()
来打印价格。
答案 2 :(得分:1)
当你调用getTotal(Inside printTotal)时,你调用的是getPrice,它本身就有
System.out.println("Price is: " + price);
因此当你调用getTax时,你再次调用getPrice
double tax = (0.1 * getPrice());
然后调用println,这就是它打印两次的原因。