显示商品批发信息;输入批发商品编号和数量,以制定格式显示价格和总金额 使用StringBuffer类的insert()方法来实现需求
时间: 2024-04-12 21:31:13 浏览: 6
你可以使用以下代码片段来实现你的需求:
```java
import java.util.HashMap;
public class WholesaleInformation {
private HashMap<String, Double> priceList;
public WholesaleInformation() {
// 初始化商品价格列表
priceList = new HashMap<>();
priceList.put("001", 10.0);
priceList.put("002", 20.0);
priceList.put("003", 30.0);
}
public String getWholesaleInformation(String code, int quantity) {
if (!priceList.containsKey(code)) {
return "无效的商品编号";
}
double price = priceList.get(code);
double totalAmount = price * quantity;
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append("商品编号: ").append(code).append("\n");
stringBuffer.append("商品单价: ").append(price).append("\n");
stringBuffer.append("购买数量: ").append(quantity).append("\n");
stringBuffer.append("总金额: ").append(totalAmount).append("\n");
return stringBuffer.toString();
}
public static void main(String[] args) {
WholesaleInformation wholesaleInformation = new WholesaleInformation();
// 示例输入
String code = "002";
int quantity = 5;
String result = wholesaleInformation.getWholesaleInformation(code, quantity);
System.out.println(result);
}
}
```
这段代码定义了一个`WholesaleInformation`类,其中`priceList`是一个`HashMap`,用于存储商品编号和价格的对应关系。`getWholesaleInformation`方法接受商品编号和数量作为参数,根据这些信息计算总金额,并使用`StringBuffer`来构建结果字符串。最后,我们在`main`方法中提供了一个示例输入来测试代码。你可以根据自己的需求修改和扩展这段代码。