Java 方法和对象 1:many 关系

Java methods&objects 1:many relationship

在我的任务中,我将创建两个 classes:Entry 和 Roster。两个 classes 之间有一个 link,应使用以下指令创建方法:

条目

数据--> Entry 具有三个私有实例变量:firstName、lastName 和 grade。 名字都是字符串,成绩是整数。

方法-->(不要添加其他方法) -Entry (String firstIn, String lastIn, int gradeIn) 构造函数

-String toString () Return 一个字符串,名称和等级由制表符分隔。 将名字格式化为姓氏,名字

-boolean equals(Entry) Return 如果 Entry 参数中的名称匹配则为真 当前对象中的名称。 Return 如果不匹配则为 false。

-int getGrade() Return对象中的成绩值

花名册

Data--> Roster 有一个 ArrayList 的 Entry 对象和一个常量 NOT_FOUND。你 必须为此分配使用 ArrayList。

方法(不要添加其他方法-->

-Roster()实例化ArrayList。 ArrayList 初始化为空。

-void insert (Entry) 使用私有搜索方法搜索列表(如下)。如果 该条目不在花名册中,请将其添加到列表中的最后一个。如果该名称已在花名册中,则什么也不做。

-void delete (Entry) 使用私密搜索方式搜索列表(如下)。如果 有条目匹配,删除条目。如果没有匹配,做 没有什么。顺序必须保持不变。

-void printAll () 打印花名册中的所有条目,每个条目都在自己的行上。

-double average() 将花名册中的平均成绩计算为double

-private int search (Entry) 实现线性搜索算法以处理 Entry 的 ArrayList。在Entry中使用equals方法 class判断是否匹配。等级不用于相等 查看。注意:使用 for 循环或从循环中断的解决方案不是 可以接受。

这是我编写的条目和花名册 classes:

    public class Entry {
private String firstName;
private String lastName;
private int grade;

public Entry(String firstIn, String lastIn, int gradeIn) {
    firstName = firstIn;
    lastName = lastIn;
    grade = gradeIn;
}

public String toString() {
    return (lastName + ", " + firstName + "\t" + grade);
}

public boolean equals(Entry entryIn) {
    if (firstName.equals(entryIn.firstName) 
            && lastName.equals(entryIn.lastName)) {
        return true;
    }
    else {
        return false;
    }
}

public int getGrade(){
    return grade;
}
}

这是我的花名册class

    import java.util.ArrayList;

public class Roster {
private static ArrayList<Entry> entries;
private final int NOT_FOUND = -1;

public Roster() {
    entries = new ArrayList<Entry>();
}

public void insert(Entry entryIn) {
    if (search(entryIn) > -1) {
        entries.add(entryIn);
    }
    else {

    }
}

public void delete(Entry entryIn) {
    int size = entries.size();
    if (search(entryIn) > -1) {
        entries.remove(search(entryIn));
        size--;
    }
}

public void printAll() {
    for (Entry entryIn : entries) {
        System.out.println(entryIn);
    }
}

public static double average() {
    double average = 0.0;
    for (int i = 1; i < entries.size(); i++) {
            average += entries.get(i).getGrade();
        } 
    return average/entries.size();
    }

private int search(Entry entryIn) {
    boolean found = false;
    int index = 0;
    while (index < entries.size() && !found) {
        if(entries.get(index).equals(entryIn)) {
            found = true;
        }
        else {
            index++;
        }
        if (index == entries.size()) {
            index = -1;
        }
    return index;
    }
    return index;

}
}

这是我得到的主要方法:

    //package project7;
import java.util.*;

public class Project7 {

/* 
 * Eight test cases for Roster
 */

    /* main method to control tests to be performed.
     * 
     */
    public static void main (String [] args)
    {
        char ch;
        boolean end = false;
        do
        {
            ch = getCommand();
            switch (ch)
            {
                case '1' :  test1();
                            break;
                case '2' :  test2();
                            break;
                case '3' :  test3();
                            break;
                case '4' :  test4();
                            break;
                case '5' :  test5();
                            break;
                case '6' :  test6();
                            break;
                case '7' :  test7();
                            break;
                case '0' :  end = true;
                            break;
            }
        }
        while (!end);
        System.out.println ("Program complete");
    }       

    /* prompt the user to enter a test number and return it as a character
     * 
     */

    static char getCommand ()
    {
        final Scanner input = new Scanner (System.in);
        char command;
        boolean valid;

        do {
            System.out.println ();
            System.out.print ("Enter test number (1..7) (0 to stop): ");
            String answer = input.next();
            command = answer.charAt(0);
            valid = command >= '0' && command <= '7';
            if (!valid)
                System.out.println ("Entry not valid, enter again");
        } while (!valid);
        return command;
    }

    /* test 1 - empty book
     */

    static void test1()
    {

        System.out.println ("Test 1: Entry");

        Entry entry1 = new Entry ("Joe", "Smith", 100);

        System.out.println ("Expecting: Smith, Joe  100");
        System.out.println ("Result: " + entry1);
        System.out.println ();

        System.out.println ("Expecting: true");
        System.out.println ("Result: " + entry1.equals(entry1));
        System.out.println ();

        System.out.println ("Expecting: false");
        Entry entry2 = new Entry ("Bill", "Jones", 0);
        System.out.println ("Result: " + entry1.equals(entry2));
        System.out.println ();

        System.out.println ("Expecting: 100");
        System.out.println (entry1.getGrade());
    }

    /* test 2 - empty Roster
    */

    static void test2()
    {
        System.out.println ("Test2: empty");
        System.out.println ();

        Roster book = new Roster ();
        System.out.println ("Expecting nothing");
        book.printAll();

        System.out.println ("Expecting 0.0");
        System.out.println (book.average());
        System.out.println ();
    }

    /* test 3 - insert and search
    */

    static void test3()
    {
        System.out.println ("Test3: insert ");
        System.out.println ();

        Roster list = new Roster();
        Entry temp = new Entry ("John", "Smith", 99);
        list.insert(temp);
        System.out.println ("Expecting Smith, John  99");
        list.printAll();
        System.out.println ();

        list.insert (new Entry ("Tom", "Jones", 78));
        list.insert (new Entry ("Fred", "Flintstone", 55));
        list.insert(new Entry ("Jill", "St. John", 79));
        list.insert(new Entry ("Jim", "Smith", 88));
        System.out.println ("Expecting 5 entries");
        list.printAll();
        System.out.println ();

        System.out.println ("Expecting 79.8");
        System.out.println (list.average());
    }

    /* test 4 - insert with duplicates
    */

    static void test4()
    {
        System.out.println ("Test4: Duplicate Entries ");
        System.out.println ();

        Roster book = new Roster();
        book.insert(new Entry ("John", "Bob", 77));
        book.insert(new Entry ("Jim","Bob", 89));
        book.insert(new Entry ("John", "Bob", 89));
        book.insert(new Entry ("Jim","Bob", 55));

        System.out.println ("Expecting 2 entries");
        book.printAll();
        System.out.println ();
    }

    /* test 5 - deleting
    */      

static void test5()
    {
        System.out.println ("Test5: Deleting");
        System.out.println ();

        Roster list = new Roster ();
        list.insert(new Entry ("John", "Johnson", 77));
        list.insert(new Entry ("Tom","Thompson", 99));
        list.insert(new Entry ("Jeff", "Jefferson", 44));
        list.insert(new Entry ("Fred", "Fredrickson", 91));
        list.insert(new Entry ("Tina", "Tina", 95));

        System.out.println ("Expecting 5 entries");
        list.printAll();
        System.out.println ();

        System.out.println ("Expecting 4 entries");
        list.delete(new Entry ("John", "Johnson", 0));
        list.printAll();
        System.out.println ();

        System.out.println ("Expecting 3 entries");
        list.delete(new Entry ("Tina", "Tina", 0));
        list.printAll();
        System.out.println ();

        System.out.println ("Expecting 2 entries");
        list.delete(new Entry ("Fred", "Fredrickson", 0));
        list.printAll();
        System.out.println ();

        System.out.println ("Expecting 1 entry");
        list.delete(new Entry ("Tom", "Thompson", 0));
        list.printAll();
        System.out.println ();

        System.out.println ("Expecting 0 entries");
        list.delete(new Entry ("Jeff", "Jefferson", 0));
        list.printAll();

        System.out.println ();

    }


    /* test 6 - delete duplicates
     */

    static void test6() {
        System.out.println ("Test6: delete duplicates");
        System.out.println ();

        // create new book and fill
        Roster list = new Roster ();

        list.insert(new Entry ("John", "Johnson", 77));
        list.insert(new Entry ("Tom","Thompson", 99));
        list.insert(new Entry ("Jeff", "Jefferson", 44));
        list.insert(new Entry ("Fred", "Fredrickson", 91));
        list.insert(new Entry ("Tina", "Tina", 95));

        System.out.println ("Expecting all");
        list.printAll();
        System.out.println ();

        System.out.println ("Expecting 4 entries");
        list.delete(new Entry ("Jeff", "Jefferson", 0));
        list.printAll();
        System.out.println ();

        System.out.println ("Expecting 4 entries");
        list.delete(new Entry ("Jeff", "Jefferson", 0));
        list.printAll();
        System.out.println ();

    }       

    /* test 7- empty and fill
     */

    static void test7 () {
        Roster list = new Roster ();
        list.insert(new Entry ("John", "Johnson", 77));
        list.insert(new Entry ("Tom","Thompson", 99));
        list.insert(new Entry ("Jeff", "Jefferson", 44));

        System.out.println ("Expecting 3 entries");
        list.printAll();
        System.out.println ();

        list.delete(new Entry ("John", "Johnson", 0));
        list.delete(new Entry ("Tom", "Thompson", 0));
        list.delete(new Entry ("Jeff", "Jefferson", 0));

        System.out.println ("Expecting 0 entries");
        list.printAll();
        System.out.println ();

        list.insert(new Entry ("John", "Johnson", 87));
        list.insert(new Entry ("Tom","Thompson", 76));
        list.insert(new Entry ("Jeff", "Jefferson", 83));

        System.out.println ("Expecting 3 entries");
        list.printAll();
        System.out.println ();

    }   
}

代码运行但没有给出预期的输出。我很难在搜索方法中编写线性搜索 ArrayList 的代码,我认为这些错误会渗透到 insert/delete 方法中。如果有人对如何修复这些方法有建议,我将不胜感激。我对编程很陌生。谢谢!

您的主要问题在于您的搜索方法以及您设置索引的方式/您返回的索引....

你的 average 方法和 insert 方法也有错误。有小的但是很繁琐。

尝试跟踪您的代码,看看您是否可以看到当您单步执行搜索方法时会发生什么。如果您仍然无法弄清楚,请发表评论。这是一个家庭作业,我不会只给你你不会那样做的答案。

还有,下次一定要把预期产出和实际结果放上去。这避免了我们必须获取您的代码并 运行 它,因为并非所有人都有时间这样做。

我们开始了。

测试 2:

您的平均函数不需要是静态的。您还应该检查该函数中列表的大小是否为空,这样您就不会尝试 return 一个可能的 "something divided by 0"。如果列表为空,直接 return 0.0

if (entries.size() == 0) {
    return 0.0;
}

您可能还想将 for 循环更改为:

for (Entry x : entries) {
    average += x.getGrade();
}

你现在的那个是错误的。它从 0 开始计数。for each 循环更清晰。

测试 3:

问题出在你的搜索功能上。这里有几处错误 - 首先,这个;

while (index < entries.size() && !found) {
    if (entries.get(index).equals(entryIn)) {
        found = true;
    } else {
        index++;
    }
    if (index == entries.size()) {
        index = -1;
    }
    return index;
}

这个循环从根本上来说是错误的,因为在第一次循环结束时,你立即退出了这个函数。您实际上并没有遍历整个列表。将 return index; 放在 if (index == ....) 块中。

其次,.size() 从 1 开始计数,而不是 0。索引从 0 开始。这意味着您永远不会达到那种情况。 (顺便说一句,你的 while 循环条件是 < size() 这是正确的,但这字面意思是索引永远不会 == size()

此外,整个函数可以简化为:

for (Entry x : entries) {
    if (x.equals(entryIn)) {
        return entries.indexOf(x); // if you find it, return the index.
    }
}

return -1; // if you didn't return already, you didn't find it. so return -1

但这还不足以修复测试 3。您的插入函数仍然存在错误。

if (search(entryIn) > -1) {
    entries.add(entryIn); // are you sure it should be here?
} else {

}

通过将添加条目放入 if 块中,您实际上是在说。 "If i search for this entry and find an index that is bigger than -1, add it." 这意味着 "If it already exists, add it." 关于你的 IDK,但这对我来说没有多大意义。对于以后的测试,请尝试大声朗读 if/else 检查背后的含义,并问问自己 "Does it make sense?"

正如您自己注意到的那样,您的代码中存在大量小错误,只是一些小错误。如果你自己测试每一个并一次修复它们,你的程序会很快自己理顺。事实上,通过修复这些问题,您的整个程序通过了所有测试(据我所知,因为我没有真正阅读您的作业要求)。

无论如何请阅读评论中的如何提问 link,以防您有其他问题。请帮我一个忙,因为我刚刚花了时间调试您的代码。