Java商品买进售出代码
时间: 2024-05-16 16:19:47 浏览: 14
以下是Java中的商品买进售出代码示例:
```java
import java.util.Scanner;
public class Product {
private String name;
private int quantity;
private double costPrice;
private double sellingPrice;
public Product(String name, int quantity, double costPrice, double sellingPrice) {
this.name = name;
this.quantity = quantity;
this.costPrice = costPrice;
this.sellingPrice = sellingPrice;
}
public void buy(int quantity, double costPrice) {
this.quantity += quantity;
this.costPrice = ((this.costPrice * this.quantity) + (costPrice * quantity)) / (this.quantity + quantity);
}
public void sell(int quantity) {
if (this.quantity >= quantity) {
this.quantity -= quantity;
System.out.println("Total Selling Price: " + (quantity * sellingPrice));
} else {
System.out.println("Insufficient Quantity!");
}
}
public void printDetails() {
System.out.println("Product Name: " + name);
System.out.println("Available Quantity: " + quantity);
System.out.println("Cost Price: " + costPrice);
System.out.println("Selling Price: " + sellingPrice);
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter Product Name: ");
String name = scanner.nextLine();
System.out.print("Enter Quantity: ");
int quantity = scanner.nextInt();
System.out.print("Enter Cost Price: ");
double costPrice = scanner.nextDouble();
System.out.print("Enter Selling Price: ");
double sellingPrice = scanner.nextDouble();
Product product = new Product(name, quantity, costPrice, sellingPrice);
product.printDetails();
System.out.print("Enter Quantity to Buy: ");
int buyQuantity = scanner.nextInt();
System.out.print("Enter Cost Price: ");
double buyCostPrice = scanner.nextDouble();
product.buy(buyQuantity, buyCostPrice);
product.printDetails();
System.out.print("Enter Quantity to Sell: ");
int sellQuantity = scanner.nextInt();
product.sell(sellQuantity);
product.printDetails();
scanner.close();
}
}
```
这个示例程序创建了一个商品类,其中包含商品的名称、可用数量、成本价格和销售价格。它还包括购买和销售商品的方法,并在控制台上打印商品的详细信息。程序通过用户输入来获取商品的详细信息,然后通过调用相应的方法来模拟购买和销售商品的过程。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)