Программа кругового двусвязного списка на Java (справка по домашнему заданию) - PullRequest
1 голос
/ 17 февраля 2012

В основном программа должна создать «круглый стол» руководителей с председателем, которого нельзя сменить. Я почти знаю, что я делаю, и я почти нахожусь на полпути через мои методы для вставки и удаления руководителей, но я просто попытался проверить свой код, чтобы увидеть, как он идет, и он получает ошибки, как только я ввожу председателей Информация. Кроме того, я не совсем уверен, как бы я поступил с методом removeByCorporation в ExecutiveList. Я почти уверен, что метод почти все неверен, и я просто не знаю, как удалить узел в круговом двусвязном списке, подобном этому.

* Нет необходимости помогать мне с методами печати, я просто еще не получил их.

ТЛ; др: 1) Почему он падает сразу? 2) Я почти уверен, что мой метод removeByCorporation совершенно неверен. Если это так, какие-либо предложения или помощь, как это исправить?

Вот два класса, с которыми у меня проблемы, если вы хотите увидеть другие, дайте мне знать, и я опубликую их, но они на 99% являются получателями и установщиками.

ПЕРВЫЙ КЛАСС

public class ExecutiveList {

private ExecutiveNode chair;
ExecutiveNode cursor;

public ExecutiveList() {

}

public ExecutiveList (Executive chairperson) {

    chair.setExecutive(chairperson);
    chair.left = chair;
    chair.right = chair;
}

public void insertLeftOfChair(Executive exec) {

    ExecutiveNode newExec = new ExecutiveNode();
    newExec.setExecutive(exec);
    chair.setLeft(newExec);

}

public boolean insertRightOfExec (Executive exec, String target) {
    cursor = chair;
    ExecutiveNode newExec = new ExecutiveNode();

    do { cursor = cursor.getLeft();
    if (cursor.getExecutive().equals(exec)) {
        newExec.setExecutive(exec);
        cursor.getRight().setLeft(newExec);
        newExec.setLeft(cursor);
        newExec.setRight(cursor.getRight());
        cursor.setRight(newExec);
        return true;
    }
    else {
        return false;
    }
    }       while (cursor.getExecutive().getExecutiveName() != target);


}

public boolean insertLeftOfExec (Executive exec, String target) {
    cursor = chair;
    ExecutiveNode newExec = new ExecutiveNode();
    do { cursor = cursor.getLeft();
        if (cursor.getExecutive().equals(exec)) {
            newExec.setExecutive(exec);
            cursor.getLeft().setRight(newExec);
            newExec.setRight(cursor);
            newExec.setLeft(cursor.getRight());
            cursor.setLeft(newExec);

            return true;
        }
        else {
            return false;
        }
    }       while (cursor.getExecutive().getExecutiveName() != target);
}

public boolean removeTargetExec(String name) {
    if (chair.equals(name)) {
        return false;
    }
    else {
        return false;
    }
}

public int removeByCorporation(String corporation) {
    int removed = 0;
    cursor = chair;
    do {
        if (cursor.getExecutive().getCompanyName().equals(corporation)) {
            cursor.setExecutive(null);
            cursor.getLeft();
            removed = removed + 1;
        }
    } while (removed > 0);

    return removed;
}

public void printByCorporation(String corporation) {

}

public void printAllClockwise() {

}

public void printAllCounterClockwise() {

}
    }

ВТОРОЙ КЛАСС

import java.util.Scanner;

    public class MeetingManager {
public static void main(String[] args) {

    // scanner to read the users input
    Scanner input = new Scanner(System.in);

    // strings to pass information about the chairperson
    String chairpersonName;
    String chairpersonCompany;

    // strings to pass information about executives other
    // than the chairperson
    String execName;
    String execCompany;
    String target;

    // holds information on whether on not an operation
    // was successful and how many executives were removed
    // for the remove by corporation command.
    boolean success;
    int numRemoved = 0;

    // prompts the user for information about the chairperson
    // and sets it to an executive object name chairperson
    System.out.println("Enter the name of the chairperson: ");
    chairpersonName = input.next();
    if (chairpersonName.length() < 1) {
        System.out.println("Please enter a full name");
    }
    System.out.println("Enter the company of the chairperson: ");
    chairpersonCompany = input.next();
    if (chairpersonCompany.length() < 1) {
        System.out.println("Please enter a full name");
    }
    Executive chairperson = new Executive(chairpersonName, chairpersonCompany);

    // creates a new ExecutiveList object and passes information
    // about the chairperson
    ExecutiveList list = new ExecutiveList(chairperson);

    // for loop to repeatedly print the menu and take instructions
    // from the user until they choose to exit.
    for (int i = 1; i > 0; i++) {
        ShowMenu();
        String option = input.next();

        // error message for improper input
        if (option.length() > 3) {
            System.out.println("You can only enter one option");
        }

        // insert left of chairperson
        else if (option.toUpperCase().equals("ILC")) {
            System.out.println("Enter the executives name: ");
            execName = input.next();
            System.out.println("Enter the executives company: ");
            execCompany = input.next();
            Executive newGuy = new Executive(execName, execCompany);
            list.insertLeftOfChair(newGuy);
            System.out.println("Insertion successful.");
        }

        // insert left of executive
        else if (option.toUpperCase().equals("ILE")) {
            System.out.println("Enter the executives name: ");
            execName = input.next();
            System.out.println("Enter the executives company: ");
            execCompany = input.next();
            Executive newGuy = new Executive(execName, execCompany);
            System.out.println("Enter the name of the target executive: ");
            target = input.next();

            success = list.insertLeftOfExec(newGuy, target);
            if (success == true) {
                System.out.println("Insertion successful.");
            }
            else {
                System.out.println("The executive could not be inserted.");
            }
        }


        // insert right of executive
        else if (option.toUpperCase().equals("IRE")) {
            System.out.println("Enter the executives name: ");
            execName = input.next();
            System.out.println("Enter the executives company: ");
            execCompany = input.next();
            Executive newGuy = new Executive(execName, execCompany);
            System.out.println("Enter the name of the target executive: ");
            target = input.next();

            success = list.insertRightOfExec(newGuy, target);
            if (success) {
                System.out.println("Insertion successful.");
            }
            else {
                System.out.println("The executive could not be inserted.");
            }
        }

        // remove target executive
        else if (option.toUpperCase().equals("RTE")) {
            System.out.println("Enter the name of the executive to remove: ");
            execName = input.next();
            success = list.removeTargetExec(execName);

            if (execName.equals(chairpersonCompany))
                list.removeTargetExec(execName);
            if (success) {
                System.out.println(execName + " has been removed from the meeting.");
            }
            else {
                System.out.println(execName + " could not be found.");
            }
        }

        // remove by corporation
        else if (option.toUpperCase().equals("RBC")) {
            System.out.println("Enter the name of the corporation to remove: ");
            execCompany = input.next();
            numRemoved = list.removeByCorporation(execCompany);
            if (execCompany.equals(chairperson.getCompanyName())) {
                System.out.println("Invalid command: cannot remove all employees from the chairperson's corporation");
            }
            else if (numRemoved < 1) {
                System.out.println("That corporation could not be found and no executives were removed.");
            }
            else {
                System.out.println(numRemoved + " executive(s) from " + execCompany + " have been removed from the meeting.");
            }
        }

        // prints by corporation
        else if (option.toUpperCase().equals("PBC")) {
            System.out.println("Enter the name of a corporation to display: ");
            execCompany = input.next();
            list.printByCorporation(execCompany);
        }

        // prints all counter-clockwise
        else if (option.toUpperCase().equals("PCC")) {

            list.printAllCounterClockwise();
        }

        // prints all clockwise
        else if (option.toUpperCase().equals("PCL")) {

            list.printAllClockwise();
        }

        else if (option.toUpperCase().equals("EXT")) {
            System.out.println("Terminating program...");
            break;
        }

        // Error message
        else {
            System.out.println("Please select a valid option.");
        }

    }

}



// displays menu and prompts user for input
public static void ShowMenu() {
    System.out.println("\nILC) Insert an executive to the left of the chairperson\nILE) Insert an executive to the left of a given executive\nIRE) Insert an executive to the right of a given executive\nRTE) Remove Target Executive");
    System.out.println("RBC) Remove By Corporation\nPBC) Print By Corporation\nPCC) Print all in counter-clockwise order\nPCL) Print all in clockwise order\nEXT) Exit the program\n\nSelect a menu option: ");
}

}

Наконец, спасибо всем, кто дает какие-либо советы, советы или реальную помощь в той или иной форме. Я знаю, что люди злятся, когда по какой-то причине видят домашнее задание, потому что думают, что ученик просит их «сделать за меня домашнее задание», но это не то, чем я занимаюсь. Я просто хотел бы получить любой совет или подсказку, я не прошу вас просто заполнить пробелы для меня и исправить все (не то, чтобы я был против этого: P). Спасибо.

Ответы [ 2 ]

1 голос
/ 17 февраля 2012

В методе removeByCorporation вы просто устанавливаете для исполнителя значение null, но, учитывая, что это список с двумя связями, вы не думаете, что вам нужно установить ссылки на предыдущий и следующий руководитель, чтобы список с двумя связями не т перерыв.

0 голосов
/ 17 февраля 2012

Хитрость заключается в том, чтобы убедиться, что при КАЖДОЙ операции вы обновляете изменяемый элемент и два других, которые ссылаются на него (довольно удобно в двусвязном списке, два, которые ссылаются на него, также являются двумя, на которые он ссылается).

Проверьте каждый из ваших методов и убедитесь, что в каждом из них вы обновляете 4 поля на изменение - два в теме и по одному в двух, связанных с темой.

...