CompareTo冒泡排序

时间:2015-02-24 09:45:17

标签: java sorting compareto

我正在尝试使用冒泡排序方法对程序中的值进行排序。我相信 organisedRoom 方法中的代码是正确的。但是,当我运行代码,添加一些客户,然后尝试对它们进行排序时,程序崩溃了。如果有人能指出我正确的方向,我将非常感激。

package test;

import java.io.IOException;
import java.util.Scanner;

public class Test {

private class Customer implements Comparable<Customer>{
    private String name;
    public Customer(String name) { 
        this.name = name;
    }

    //Override to stop the program returning memory address as string
    @Override

    public String toString() {
        return name;
    }

    @Override
    public int compareTo(Customer c) {
        return name.compareTo(c.name);
    } 
} 

//Array to store customers
public Customer[] customers;

public Scanner input = new Scanner(System.in);

public Test(int nRooms) throws IOException {
    customers = new Test.Customer[nRooms];
    System.out.println("Welcome to the Summer Tropic Hotel\n");
    chooseOption();

}

final JFileChooser fc = new JFileChooser();

// Call new Hotel with int value to allocate array spaces
public static void main(String[] args) throws IOException {

    Test t = new Test(11);

}

// New procedure to return User input and point to next correct method
private String chooseOption() throws IOException {

    // Set to null, this will take user input
    String choice;

    //Menu options
    System.out.println("This is the Hotel Menu. Please choose from the following options:\n");
    System.out.println("A: " + "This will add a new entry\n");
    System.out.println("O: " + "View booked rooms, in order of customers name.\n");
    System.out.println("X: " + "Exit the program\n");

    // Take user input and assign it to choice
    choice = input.next();

    // Switch case used to return appropriate method
    switch (choice.toUpperCase()) {
        case "A" :
            System.out.println("");
            addCustomer();
            return this.chooseOption();

        case "O" :
            System.out.println("");
            organisedRoom();
            return this.chooseOption();

        case "X":
            System.exit(0);               

    }
    return choice;
}

// Add a new customer to the Array
public void addCustomer() throws IOException {

    // New variable roomNum
    int roomNum = 1;

    // Loop
    do {

        // Take user input as room number matching to array index - 1
        System.out.println("Please choose a room from 1 to 10");
        roomNum = input.nextInt() - 1;

        // If room is already booked print this
        if (customers[roomNum] != null) {
            System.out.println("Room " + roomNum + 1 + " is not free, choose a different one.\n");
            this.addCustomer();
        }

    // Do until array index does not equal to null
    } while (customers[roomNum]!= null);

    System.out.println("");

    // User input added to array as name replacing null (non case-sensetive)
    System.out.println("Now enter a name");
    customers[roomNum] = new Customer(input.next().toLowerCase());

    // Customer (name) added to room (number)
    System.out.println(String.format("Customer %s added to room %d\n", customers[roomNum], roomNum + 1));          
}

private void organisedRoom() {

    boolean flag = true;
    Customer temp;
    int j;

    while (flag) {
        flag = false;
        for (j = 0; j < customers.length - 1; j++) {
            if (customers[j].compareTo(customers[j+1]) < 0) {
                temp = customers[j];
                customers[j] = customers[j + 1];
                customers[j + 1] = temp;
                flag = true;
            }
        }
    }
}
}

我认为这是因为数组的初始化会为所有数组索引位置添加null。

堆栈跟踪如下:

Exception in thread "main" java.lang.NullPointerException
    at test.Test$Customer.compareTo(Test.java:34)
    at test.Test.organisedRoom(Test.java:133)
    at test.Test.chooseOption(Test.java:83)
    at test.Test.chooseOption(Test.java:79)
    at test.Test.chooseOption(Test.java:79)
    at test.Test.<init>(Test.java:46)
    at test.Test.main(Test.java:55)
Java Result: 1

2 个答案:

答案 0 :(得分:0)

它失败了,因为您创建的Customer[]将使用11个null引用进行初始化。如果您想订购它们将比较阵列中的所有元素。哪个引导到java.lang.NullPointerException

Customer存储在ArrayList中。然后你应该能够防止这个错误。

修改
如果你真的需要尽可能地贴近你当前的代码。以下将修复您的排序。 (不要将此解决方案用于现实生活中的项目)

private void organisedRoom() {
    for (int i = customers.length - 1; i > 0; i--) {
        for (int j = 0; j < i; j++) {
            if (customers[j + 1] == null) {
                continue;
            }
            if (customers[j] == null ||customers[j + 1].compareTo(customers[j]) < 0) {
                Customer temp = customers[j + 1];
                customers[j + 1] = customers[j];
                customers[j] = temp;
            }
        }
    }
    System.out.println("show rooms: " + Arrays.toString(customers));
}

编辑2
为了保留当前的大部分代码,您可以将房间存储在Customer实例中(我个人不喜欢)。

// change the constructor of Customer
public Customer(String name, int room) {
    this.name = name;
    this.room = room;
}

// change the toString() of Customer
public String toString() {
    return String.format("customer: %s  room: %d", name, room);
}

// store the Customer like
customers[roomNum] = new Customer(input.next().toLowerCase(), roomNum);

答案 1 :(得分:0)

您对Bubble Sort的实现不正确。它使用嵌套for循环。

for(int i = 0; i < customers.length; i++)
{
    for(int j = 1; j < (customers.length - i); j++)
    {
        if (customers[j-1] > customers[j]) 
        {
            temp = customers[j-1];
            customers[j-1] = customers[j];
            customers[j] = temp;
        }
    }
}