java - 第一年编程作业出现问题

标签 java

我是一名计算机科学一年级学生,在部分作业中遇到问题。作业的目标是存储多项式的系数并使用数组和链表查找其根。我能够成功完成阵列版本;然而链接列表让我很头疼。

我能够成功存储polynomial.java中提供的第一轮变量;然而,一旦开始计算根,事情就会变得有点疯狂,并且程序最终终止而没有给出任何根。我有一种感觉,这可能是由 Polynomial.java 计算根的方式引起的,导致链表出现问题;但是,我不允许更改 polynomial.java,只能更改 LinkedIntList.java。在过去的 7 个小时里,我一直在用头撞电脑,试图找到这个 bug,现在我准备放弃这个作业了,因为我无法联系到教授寻求帮助。

我非常感谢任何能够发现错误或愿意查看代码以提供有关我可能做错了什么或如何解决我的问题的提示。

文件1:Node.Java

package lists;

public class Node
{
    int element;
    Node next = null;

    /**
     * Constructor which creates a new node containing the value specified by item
     *
    */
    public Node (int item)
    {
        element = item;
    }

    /**
     * Returns the current value of the data item contained inside this node
     */
    public int getElement ()
    {
        return element;
    }

    /**
     * Sets the current value of the data item contained inside this node to
     * the value specified by newVal
     */
    public void setElement (int newVal)
    {
        element = newVal;
    }

    /**
     * Links this node to the node passed in as an argument
     */ 
    public void setNext (Node n)
    {
        next = n;
    }

    /**
     * Returns a reference to the node that follows this node in the
     * linked list, or null if there is no such node
     */
    public Node getNext ()
    {
        return next;
    }

    /**
     * Returns a string based representation of the data item contained
     * in this node.
     */
    public String toString()
    {
        return Integer.toString(element);
    }   
}

文件2:LinkedIntList.Java

    package lists;

    public class LinkedIntList implements IntList
    {

        Node head = null;
        int count = 0;
        /**
         * Standard Java toString method that returns a string
         * equivalent of the IntList
         *
         * @return  a string indicating the values contained in 
         *          this IntList (ex: "[5 3 2 9 ]")
         */
        public String toString()
        {
            String retVal = "";
            String intermediary = "";
            Node n;
            for (n = head; n.getNext() != null; n = n.getNext())
            {
                intermediary = Integer.toString(n.getElement());
                retVal = intermediary + " " + retVal;
            }
            retVal = n.getElement() + " " + retVal;
            return retVal;
        }

        /**
         * Adds the given value to the <b>end</b> of the list.
         *
         * @param value  the value to add to the list
         */
        public void add (int value)
        {
            Node newNode = new Node (value);

            if (head == null)
                head = newNode;
            else
            {
                Node n = head;
                while (n.getNext() != null)
                {
                    n = n.getNext();
                }
                n.setNext(newNode);
            }
            count++;
        }

        /**
         * Returns the number of elements currently in the list.
         *
         * @return   the number of items currently in the list
         */
        public int size()
        {
            return count;
        }

        /**
         * Returns the element at the specified position in this list.
         *
         * @param index  index of the element to return (zero-based)
         * @return the element at the specified position in this list. 
         * @throws IndexOutOfBoundsException  if the index is out of range 
         *                                    (index < 0 || index >= size()). 
         */
        public int get(int index) throws IndexOutOfBoundsException
        {
            Node reference = head;
            if (index < 0 || index >= count)
            {
                throw new IndexOutOfBoundsException("Index out of bounds.");
            }
            for (int i = 0; i != index; i++)
                {
                    reference.getNext();
                }
            return reference.getElement();
        }

        /**
         * Replaces the element at the specified position in this list with 
         * the specified element. 
         *
         * @param index  index of the element to return (zero-based)
         * @param value  element to be stored at the specified position.
         * @throws IndexOutOfBoundsException  if the index is out of range 
         *                                    (index < 0 || index >= size()). 
         */
        public void set (int index, int value) throws IndexOutOfBoundsException
        {
            if (index < 0 || index >= count)
            {
                throw new IndexOutOfBoundsException("Index out of bounds.");
            }
            Node newNode = new Node (value);
            Node trailingReference = head;
            Node leadingReference = head.getNext();
                    for(int i = 1; i != index; i++)
                    {
                        trailingReference = leadingReference;
                        leadingReference = leadingReference.getNext();
                    }
            trailingReference.setNext(newNode);
            newNode.setNext(leadingReference);
            count++;
        }
    }

文件3:IntList.Java

        package lists;

        public interface IntList
        {
            /**
             * Standard Java toString method that returns a string
             * equivalent of the IntList
             *
             * @return  a string indicating the values contained in 
             *          this IntList (ex: "[5 3 2 9 ]")
             */
            public String toString();

            /**
             * Adds the given value to the <b>end</b> of the list.
             *
             * @param value  the value to add to the list
             */
            public void add (int value);

            /**
             * Returns the number of elements currently in the list.
             *
             * @return   the number of items currently in the list
             */
            public int size();

            /**
             * Returns the element at the specified position in this list.
             *
             * @param index  index of the element to return (zero-based)
             * @return the element at the specified position in this list. 
             * @throws IndexOutOfBoundsException  if the index is out of range 
             *                                    (index < 0 || index >= size()). 
             */
            public int get(int index);

            /**
             * Replaces the element at the specified position in this list with 
             * the specified element. 
             *
             * @param index  index of the element to return (zero-based)
             * @param value  element to be stored at the specified position.
             * @throws IndexOutOfBoundsException  if the index is out of range 
             *                                    (index < 0 || index >= size()). 
             */
            public void set (int index, int value);
        }

文件 4:Polynomial.java

/**
 * A program which finds the integer (whole number) roots of a
 * polynomial with integer coeffecients.  The method used is based
 * upon the ideas presented at:
 *
*/

import lists.*;

public class Polynomial
{
    public static void main (String [] args)
    {
        // trick to get out of static context
        new Polynomial().runMe();
    }

    public void runMe()
    {

        IntList poly = new LinkedIntList();

        // Create the polynomial:
        // 3x^10 + 12x^9 - 496x^8 - 211x^7 + 18343x^6 -43760x^5 + 
        //    11766x^4 + 26841x^3 - 126816x^2 + 37278x - 84240
        poly.add (-84240);
        poly.add (37278);
        poly.add (-126816);
        poly.add (26841);
        poly.add (11766);
        poly.add (-43760);
        poly.add (18343);
        poly.add (-211);
        poly.add (-496);
        poly.add (12);
        poly.add (3);

        System.out.print ("Finding the integer roots of the polynomial: ");
        System.out.println (poly);
        IntList roots = findRoots (poly);

        for (int x = 0; x < roots.size(); x++)
            System.out.println ("Root found: " + roots.get(x));
    }

    /**
     * Find all *integer* roots of the polynomial represented by the IntList.
     * 
     * @param poly    a polynomial encoded as a list of coefficients
     * @return     a list of all roots of the given polynomial. Note that
     *         the returned list may have duplicate entries. 
     */
    public IntList findRoots (IntList poly)
    {
        IntList l = new LinkedIntList();  

        int q = poly.get(poly.size() - 1);
        int p = poly.get(0);

        IntList pVals = divTerms(Math.abs(p));
        IntList qVals = divTerms(Math.abs(q));

        IntList possibleZeros = findPotentialZeros(pVals, qVals);

        //for (Integer i : possibleZeros)
        for (int x = 0; x < possibleZeros.size(); x++)
            if (eval (poly, possibleZeros.get(x)) == 0)
                l.add (possibleZeros.get(x));

        return l;
    }

    /**
     * Evaluates the polynomial represented by the IntList with the given
     * value.
     *
     * @param poly    a 
     * @param val    the value to evaluate the polynomial with.
     * @return    f(val), where f is the polynomial encoded as poly
     */
    private int eval (IntList poly, int val)
    {
        int result = 0;
        for (int x = poly.size() - 1; x >= 0; x--)
            result += poly.get(x) * (int) Math.pow (val, x);  

        return result;

    }

    private IntList findPotentialZeros (IntList plist, IntList qlist)
    {

        IntList result = new LinkedIntList();

        for (int p = 0; p < plist.size(); p++)
        {
            for (int q = 0; q < qlist.size(); q++)
            {
                // add it only if q evenly divides p (we're looking
                // for integer roots only
                if (plist.get(p) % qlist.get(q) == 0)
                {
                    int x = plist.get(p) / qlist.get(q);
                    result.add (x);
                    result.add (-x);
                }
            }
        }
        return result;
    }


    /**
     * Find all integers that evenly divide i.
     *
     * @param i    the integer to find all divisors of
     * @return a list of all integers that evenly divide i
     */
    private IntList divTerms (int i)
    {

        IntList v = new LinkedIntList();  


        // 1 divides all numbers
        v.add(1);

        // find all divisors < i and >= 2
        for (int x = 2; x < i; x++)
            if (i % x == 0)
                v.add(x);

        // all numbers are evenly divisible by themselves
        if (i > 1) 
            v.add(i);

        return v;
    } 
}

最佳答案

我认为,错误(或其中之一)是在您的 LinkedList 实现中,正是在 get 方法中:

    public int get(int index) throws IndexOutOfBoundsException
    {
        Node reference = head;
        if (index < 0 || index >= count)
        {
            throw new IndexOutOfBoundsException("Index out of bounds.");
        }
        for (int i = 0; i != index; i++)
            {
                reference.getNext(); // <--- the mistake is here
            }
        return reference.getElement();
    }

您的引用始终引用列表的头部。

如果您被允许使用任何 java 包 - 请使用 java.util.LinkedList。否则,请使用 java.util.LinkedList,直到程序的所有其他部分都完成并测试并按您希望的方式工作。之后小心地将其替换为您的 LinkedList 实现。

关于java - 第一年编程作业出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3948486/

相关文章:

java - 写入或读取文件

java - 从字符串中的byte[]到字符串?

java - 如何从java查询eXist数据库

java - 使用参数将数据从 Activity 发送到 Fragment (Kotlin/Android)

java - JSR-352 Batchlet ejb nullPointerException

java - 对快速排序和合并排序进行基准测试得出合并排序更快

JAVA SPRING MVC 在页面上显示之前修改输出流

java.security.NoSuchAlgorithmException : Ed25519 KeyPairGenerator not available

java - 在 asynctask 结束时执行一个函数

用于开发益智游戏(例如 Jigsaw)的 Java 框架