用java编写一个超市购物程序,实现超市购物功能。购物时,如果购物者所要购买的商品在超市中有,则提示购物者买到了商品;如果超市中没有购物者所需的商品,则提示购物者白跑了一趟,在超市中什么都没有买到。
时间: 2024-03-01 21:55:23 浏览: 40
好的,我可以为您提供一些参考代码来实现超市购物程序。首先是商品类:
```java
public class Commodity {
private String name; // 商品名称
private double price; // 商品价格
public Commodity(String name, double price) {
this.name = name;
this.price = price;
}
public String getName() {
return name;
}
public double getPrice() {
return price;
}
}
```
然后是超市类:
```java
import java.util.ArrayList;
public class Supermarket {
private ArrayList<Commodity> commodities; // 超市中的商品列表
public Supermarket() {
commodities = new ArrayList<Commodity>();
}
public void addCommodity(Commodity commodity) {
commodities.add(commodity);
}
public boolean hasCommodity(String name) {
for (Commodity commodity : commodities) {
if (commodity.getName().equals(name)) {
return true;
}
}
return false;
}
}
```
接下来是购物者类:
```java
import java.util.Scanner;
public class Shopper {
private String name; // 购物者姓名
public Shopper(String name) {
this.name = name;
}
public void buyCommodity(Supermarket supermarket) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入您要购买的商品名称:");
String commodityName = scanner.nextLine();
if (supermarket.hasCommodity(commodityName)) {
System.out.println("恭喜您,购买成功!");
} else {
System.out.println("很遗憾,超市中没有您要购买的商品。");
}
}
}
```
最后是主程序:
```java
public class Main {
public static void main(String[] args) {
// 创建超市并添加商品
Supermarket supermarket = new Supermarket();
supermarket.addCommodity(new Commodity("苹果", 5.0));
supermarket.addCommodity(new Commodity("香蕉", 3.0));
supermarket.addCommodity(new Commodity("西瓜", 10.0));
// 创建购物者并购买商品
Shopper shopper = new Shopper("小明");
shopper.buyCommodity(supermarket);
}
}
```
在程序中,我们首先创建了一个超市对象并添加了一些商品,然后创建了一个购物者对象并让其购买商品。在购买时,我们调用超市对象的hasCommodity方法来检查超市中是否有购物者所需的商品,如果有则提示购买成功,否则提示购物者白跑了一趟。
希望这份代码对您有所帮助!
相关推荐
![java](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_lunwen.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)