You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java安卓开发:如何用比较法排序订单数据?冒泡排序失效求助

解决安卓订单数据的冒泡排序问题

嘿,作为Java新手遇到这个排序问题很正常——咱们先拆解下核心问题:你当前的代码只处理单次订单,没有保存历史订单的集合,根本没有可排序的数据源!这就是你的冒泡排行使不起来的原因。下面一步步帮你实现需求:

1. 先封装订单数据:创建Order类

首先得把每个订单的信息打包成一个实体类,这样排序时才能方便地比较各个字段:

public class Order {
    private String customerName;
    private boolean hasWhippedCream;
    private boolean hasChocolate;
    private int quantity;
    private int totalPrice;

    // 构造方法,用来创建订单实例
    public Order(String customerName, boolean hasWhippedCream, boolean hasChocolate, int quantity, int totalPrice) {
        this.customerName = customerName;
        this.hasWhippedCream = hasWhippedCream;
        this.hasChocolate = hasChocolate;
        this.quantity = quantity;
        this.totalPrice = totalPrice;
    }

    // Getter方法,排序时需要获取字段值来比较
    public String getCustomerName() { return customerName; }
    public boolean isHasWhippedCream() { return hasWhippedCream; }
    public boolean isHasChocolate() { return hasChocolate; }
    public int getQuantity() { return quantity; }
    public int getTotalPrice() { return totalPrice; }

    // 重写toString,方便后续展示订单信息
    @Override
    public String toString() {
        return "Name: " + customerName +
                "\nAdd whipped cream? " + hasWhippedCream +
                "\nAdd chocolate? " + hasChocolate +
                "\nQuantity: " + quantity +
                "\nTotal: $" + totalPrice +
                "\n-------------------------\n";
    }
}

2. 在MainActivity中添加订单集合

在MainActivity里声明一个全局的列表,用来存储每次提交的订单:

public class MainActivity extends AppCompatActivity {
    int quantity = 2;
    // 新增:用来保存所有历史订单的列表
    private List<Order> orderList = new ArrayList<>();

    // ... 你原有的onCreate等方法保持不变
}

3. 修改submitOrder方法,保存订单并触发排序

每次用户点击提交按钮时,把当前订单存入列表,然后调用排序方法:

public void submitOrder(View view) {
    EditText nameField = (EditText) findViewById(R.id.name_field);
    String name = nameField.getText().toString();

    CheckBox whippedCreamCheckBox = (CheckBox) findViewById(R.id.whipped_cream_checkbox);
    boolean hasWhippedCream = whippedCreamCheckBox.isChecked();

    CheckBox chocolateCheckBox = (CheckBox) findViewById(R.id.chocolate_checkbox);
    boolean hasChocolate = chocolateCheckBox.isChecked();

    int price = calculatePrice(hasWhippedCream, hasChocolate);
    
    // 新增:创建当前订单并加入列表
    Order newOrder = new Order(name, hasWhippedCream, hasChocolate, quantity, price);
    orderList.add(newOrder);

    // 调用冒泡排序,这里按总价从高到低排,你也可以换成按数量排序的方法
    bubbleSortOrdersByTotalPrice();

    // 展示排序后的所有订单(你可以保留原来的邮件发送逻辑,也可以让两者同时工作)
    showSortedOrders();

    // 原有的邮件发送代码可以保留,按需调整
    /*
    Intent intent = new Intent(Intent.ACTION_SENDTO);
    intent.setData(Uri.parse("mailto:")); 
    intent.putExtra(Intent.EXTRA_SUBJECT, "Just Java order for " + name);
    intent.putExtra(Intent.EXTRA_TEXT, createOrderSummary(name, price, hasWhippedCream, hasChocolate));
    if (intent.resolveActivity(getPackageManager()) != null) {
        startActivity(intent);
    }
    */
}

4. 实现你的冒泡排序方法

现在有了订单列表,就能用冒泡排序来排序了。比如按总价从高到低排序:

// 冒泡排序:按订单总价降序排列
private void bubbleSortOrdersByTotalPrice() {
    int listSize = orderList.size();
    // 外层循环:控制排序轮数
    for (int i = 0; i < listSize - 1; i++) {
        // 内层循环:每轮比较相邻元素,把较小的元素"冒泡"到后面
        for (int j = 0; j < listSize - i - 1; j++) {
            // 比较当前订单和下一个订单的总价,如果当前的更小就交换位置
            if (orderList.get(j).getTotalPrice() < orderList.get(j+1).getTotalPrice()) {
                // 交换两个订单的位置
                Order tempOrder = orderList.get(j);
                orderList.set(j, orderList.get(j+1));
                orderList.set(j+1, tempOrder);
            }
        }
    }
}

如果需要按数量从多到少排序,只需要修改比较条件:

// 冒泡排序:按订单数量降序排列
private void bubbleSortOrdersByQuantity() {
    int listSize = orderList.size();
    for (int i = 0; i < listSize - 1; i++) {
        for (int j = 0; j < listSize - i - 1; j++) {
            if (orderList.get(j).getQuantity() < orderList.get(j+1).getQuantity()) {
                Order tempOrder = orderList.get(j);
                orderList.set(j, orderList.get(j+1));
                orderList.set(j+1, tempOrder);
            }
        }
    }
}

5. 展示排序后的订单

先在你的activity_main.xml里加一个TextView用来展示排序后的订单:

<TextView
    android:id="@+id/sorted_orders_display"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="16dp"
    android:textSize="16sp"
    android:scrollbars="vertical"/>

然后在MainActivity里实现展示方法:

private void showSortedOrders() {
    TextView sortedOrdersView = findViewById(R.id.sorted_orders_display);
    StringBuilder orderSummary = new StringBuilder("Sorted Orders (by total price):\n\n");
    for (Order order : orderList) {
        orderSummary.append(order.toString());
    }
    sortedOrdersView.setText(orderSummary.toString());
    // 允许滚动查看多订单
    sortedOrdersView.setMovementMethod(new ScrollingMovementMethod());
}

总结下你之前的问题

你之前的代码里没有保存多个订单的集合,只有单次订单的零散数据,根本没有可排序的数据集,所以冒泡排序自然无法运行。现在通过创建Order实体类和订单列表,我们有了可以排序的数据源,冒泡排序就能正常工作啦!


内容的提问来源于stack exchange,提问作者Jack Johnson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 03:53:09