我对这个代码片段有疑问,我试图通过它解决问题。 我在这里有一个提示,它将在解释这一方面做得更好:
将多项式表示为项的有序列表,其中项按其指数以降序排列。要添加两个多项式,请遍历两个列表,并在当前迭代器位置检查两个项,从而创建第三个列表。如果一个的指数小于另一个的指数,则将较大的指数插入结果并推进列表的迭代器。如果指数相等,则使用该指数和系数之和创建一个新项,并推进两个迭代器。例如:
3x4-2x2 + 3x + 7加到2x3 + 4x-5是3x4 + 2x3-2x2 + 7x + 2
编写程序以读取和添加多项式。您应该定义一个包含指数和系数的Term类。此类应通过比较指数值来实现Comparable接口。
通过首先创建三个不同的多项式(例如A,B和C)来演示程序,每个多项式至少具有三个不同的Term对象。显示针对
的结果多项式A + B
B + C
A + C
A + B + C (Formatting issues)
在程序的输出中,使用此方法打印A,B和C多项式,然后使用上面要求的四个总和打印结果多项式
到目前为止我有什么
主要类别:
public class Main{
public static void main(String[] args)
{
// instance variables
Term t1 = new Term(3, 4);
Term t2 = new Term(-2,2);
Term t3 = new Term(3,1);
Term t4 = new Term(7,0);
// 2x3 + 4x - 5
//3x^4 - 2x^2 + 3x + 7
Term t5 = new Term(2, 3);
Term t6 = new Term(4,1);
Term t7 = new Term(-5,0);
KWLinkedList<Term> termList1 = new KWLinkedList<>();
KWLinkedList<Term> termList2 = new KWLinkedList<>();
KWLinkedList<Term> result = new KWLinkedList<>();
termList1.add(t1);
termList1.add(t2);
termList1.add(t3);
termList1.add(t4);
termList2.add(t5);
termList2.add(t6);
termList2.add(t7);
// 3x4 + 2x3 - 2x2 + 7x + 2
result = addition(termList1, termList2);
print(termList1);
print(termList2);
print(result);
//3x4 + 2x3 - 2x2 + 7x + 2 RESULT
// print(termList1);
}
public static KWLinkedList<Term> addition (KWLinkedList<Term> listA, KWLinkedList<Term> listB)
{
Iterator<Term> firstIterator = listA.listIterator(0);
Iterator<Term> secondIterator = listB.listIterator(0);
KWLinkedList<Term> result = new KWLinkedList<Term>();
Term temp1;
Term temp2;
boolean firstRun = true;
temp1 = firstIterator.next();
temp2 = secondIterator.next();
while((temp1 != null && temp2 != null) || firstRun)
{
try
{
firstRun = false;
if (temp1.compareTo(temp2) == 0)
{
System.out.println("Adding: " + temp1 + " " + temp2);
result.add(new Term(temp1.getCoefficent() + temp2.getCoefficent(),
temp1.getExponent()));
if(firstIterator.hasNext())
{
temp1 = firstIterator.next();
}
if(secondIterator.hasNext())
{
temp2 = secondIterator.next();
}
}
else if (temp1.compareTo(temp2) < 0)
{
result.add(temp2);
if(secondIterator.hasNext())
{
temp2 = secondIterator.next();
}
}
else
{
result.add(temp1);
if(firstIterator.hasNext())
{
temp1 = firstIterator.next();
}
}
}
catch(Exception e)
{
e.getMessage();
}
}
if(firstIterator.hasNext())
{
while(firstIterator.hasNext())
{
temp1 = firstIterator.next();
result.add(temp1);
}
}
if(secondIterator.hasNext())
{
while(secondIterator.hasNext())
{
temp2 = secondIterator.next();
result.add(temp2);
}
}
return result;
}
public static KWLinkedList<Term> subtraction(KWLinkedList<Term> listA, KWLinkedList<Term> listB)
{
Iterator<Term> firstIterator = listA.listIterator(0);
Iterator<Term> secondIterator = listB.listIterator(0);
KWLinkedList<Term> result = new KWLinkedList<Term>();
Term temp1;
Term temp2;
boolean firstRun = true;
temp1 = firstIterator.next();
temp2 = secondIterator.next();
while((firstIterator.hasNext() && secondIterator.hasNext()) || firstRun)
{
try
{
firstRun = false;
if (temp1.compareTo(temp2) == 0)
{
result.add(new Term(temp1.getCoefficent() - temp2.getCoefficent(),
temp1.getExponent()));
temp1 = firstIterator.next();
temp2 = secondIterator.next();
}
else if (temp1.compareTo(temp2) < 0)
{
result.add(new Term(temp2.getCoefficent() * -1, temp2.getExponent()));
temp2 = secondIterator.next();
}
else
{
result.add(temp1);
temp1 = firstIterator.next();
}
}
catch(Exception e)
{
e.getMessage();
}
}
if(firstIterator.hasNext())
{
while(firstIterator.hasNext())
{
temp1 = firstIterator.next();
result.add(temp1);
}
}
if(secondIterator.hasNext())
{
while(secondIterator.hasNext())
{
temp2 = secondIterator.next();
result.add(new Term(temp2.getCoefficent() * -1, temp2.getExponent()));
}
}
return result;
}
public static void print(KWLinkedList<Term> printList)
{
Iterator<Term> printIterator = printList.listIterator(0);
while (printIterator.hasNext())
{
System.out.print(printIterator.next() + " ");
}
System.out.println();
}}
学期班:
public class Term implements Comparable <Term>{
// instance variables
private int coefficent = 0;
private int exponent = 0;
public Term()
{
coefficent = 0;
exponent = 0;
}
public Term(int passedCoefficent, int passedExponet)
{
setCoefficent(passedCoefficent);
setExponent(passedExponet);
}
public void setCoefficent(int passedCoefficent)
{
coefficent = passedCoefficent;
}
public void setExponent(int passedExponet)
{
exponent = passedExponet;
}
public int getCoefficent()
{
return coefficent;
}
public int getExponent()
{
return exponent;
}
public String toString()
{
if(exponent != 0)
{
return coefficent + "x^" + exponent; // if exponent is
}
else
{
return coefficent + "";
}
}
public boolean equals(Object anObject)
{
//equals method which trys to check if the object to be added
if (anObject == null || getClass() != anObject.getClass())
{
return false;
}
Term otherTerm = (Term) anObject ;
return (this.coefficent == otherTerm.getCoefficent()) &&
this.exponent == otherTerm.getExponent();
}
public int compareTo(Term object)
{
// what is the purpose and why does it work \\
// because the compare just to compare to object
// exp - object.exp give you a +, -, or 0
return (this.exponent - object.exponent);
}}
KWLinkedList类:
public class KWLinkedList<E> extends AbstractSequentialList<E> {
/************************ Instance variables ****************************/
private Node<E> head = null ; // Reference to head of the list
private Node<E> tail = null ; // Reference to tail end of the list
private int size = 0; // Number of nodes in the list
/**************************** Methods *******************************/
// Add an item at the specified index.
@Override
public void add(int index, E obj) {
listIterator(index).add(obj);
}
// Get the element at position index.
@Override
public E get(int index)
{
return listIterator(index).next();
}
// Return the size of the list
@Override
public int size() {
return size;
}
public ListIterator<E> listIterator(int index) // added method
{
return new KWListIter(index) ; // returns the new list
}
/********************************** Inner Classes*******************************/
// A Node is the building block for a double-linked list.
private static class Node<E> {
private E data; // data value in the node
private Node<E> next = null; // line to next node in the list
private Node<E> prev = null; // link to previous node in the list
/**
* Construct a node with the given data value.
* @param dataItem The data value
*/
private Node(E dataItem) {
data = dataItem;
}
} //end class Node
/** Inner class to implement the ListIterator interface. */
private class KWListIter implements ListIterator<E> {
// Instance variables
private Node<E> nextItem ; // Reference to next item in the iterator
private Node<E> lastItemReturned; // Reference to the last item returned by iterator
private int index = 0; // Index of the current item
/**
* Construct a KWListIter that will reference the ith item.
* @param i The index of the item to be referenced
*/
public KWListIter(int i) {
// Validate i parameter.
if (i < 0 || i > size) {
throw new IndexOutOfBoundsException(
"Invalid index " + i);
}
lastItemReturned = null; // No item returned yet.
// Special case of last item.
if (i == size) {
index = size;
nextItem = null;
} else { // Start at the beginning
nextItem = head;
for (index = 0; index < i; index++) {
nextItem = nextItem.next;
}
}
}
public void set(E object) // added method
{
// takes the object passed in and makes sure its not null and last item returned
if(object != null && lastItemReturned != null)
{
lastItemReturned.data = object;
// sets the lastitemreturned data to the object
}
else
{
// throws exception
throw new IllegalStateException();
}
}
public int indexOf(Object anObject)
{
int indexOf = 0;
Node<E> currentIndex = head;
while (currentIndex != null)
{
if (currentIndex.equals(anObject)) // checks at run time
{
return indexOf; // returns the index
}
indexOf++; // increments the index
currentIndex = currentIndex.next; // points to the next node
}
return -1; // returns -1 if it couldnt find the index requested
}
public int lastIndexOf(Object anObject)
{
int indexOf = 0;
int last = -1;
Node<E> currentIndex = head;
while (currentIndex != null)
{
if (currentIndex.equals(anObject)) // checks at run time
{
last = indexOf; // sets the last int to the index found
}
indexOf++; // increments the index
currentIndex = currentIndex.next; // points to the next node
}
return last; // returns the last occurrence of int
}
public void addFirst(E object)
{
if(head == null) // if head is null, then adds it to the beginning since its empty
{
head = new Node<E>(object);
}
else
{
// set the object to a temp
// node then set the temps next to head and then head to the temp
Node <E> temp = new Node<E>(object);
temp.next = head;
head = temp;
}
}
public void addLast(E object)
{
if(tail == null) // if tail null then just add the object to the end/beginning since its empty
{
tail = new Node<E>(object);
}
else
{
// set the object to a temp node then set the tails next to temp and then tail to the temp
Node <E> temp = new Node<E>(object);
tail.next = temp;
tail = temp;
}
}
public E getFirst()
{
if(head == null) // does this if head is 'empty'/null
{
throw new NoSuchElementException();
}
return head.data; // returns the element contained in head
}
public E getLast()
{
if(tail == null) // does this if tail is 'empty'/null
{
throw new NoSuchElementException();
}
return tail.data; // returns the element contained in tail
}
public Iterator<E> iterator()
{
return new KWListIter(0) ; // returns a new iterator
}
public void remove() // added method
{
// makes sure lastitemreturned is not null
if(lastItemReturned != null)
{
// removes the last item from this list and then sets it to null
KWLinkedList.this.remove(lastItemReturned);
lastItemReturned = null;
}
else
{
// throws exception
throw new IllegalStateException();
}
}
/**
* Construct a KWListIter that is a copy of another KWListIter
* @param other The other KWListIter
*/
public KWListIter(KWListIter other) {
KWListIter itr = new KWListIter(0);
itr.index = other.index;
itr.lastItemReturned = other.lastItemReturned;
itr.nextItem = other.nextItem;
}
/**
* Indicate whether movement forward is defined.
* @return true if call to next will not throw an exception
*/
@Override
public boolean hasNext() {
return nextItem != null;
}
/** Move the iterator forward and return the next item.
@return The next item in the list
@throws NoSuchElementException if there is no such object
*/
@Override
public E next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
lastItemReturned = nextItem;
nextItem = nextItem.next;
index++;
return lastItemReturned.data;
}
/**
* Indicate whether movement backward is defined.
* @return true if call to previous will not throw an exception
*/
@Override
public boolean hasPrevious() {
return (nextItem == null && size != 0)
|| nextItem.prev != null;
}
/**
* Return the index of the next item to be returned by next
* @return the index of the next item to be returned by next
*/
@Override
public int nextIndex() {
return index;
}
/**
* Return the index of the next item to be returned by previous
* @return the index of the next item to be returned by previous
*/
@Override
public int previousIndex() {
return index - 1;
}
/**
* Move the iterator backward and return the previous item.
* @return The previous item in the list
* @throws NoSuchElementException if there is no such object
*/
@Override
public E previous() {
if (!hasPrevious()) {
throw new NoSuchElementException();
}
if (nextItem == null) { // Iterator past the last element
nextItem = tail;
} else {
nextItem = nextItem.prev;
}
lastItemReturned = nextItem;
index--;
return lastItemReturned.data;
}
/**
* Add a new item between the item that will be returned
* by next and the item that will be returned by previous.
* If previous is called after add, the element added is
* returned.
* @param obj The item to be inserted
*/
@Override
public void add(E obj) {
if (head == null) { // Add to an empty list.
head = new Node<E>(obj);
tail = head;
} else if (nextItem == head) { // Insert at head.
// Create a new node.
Node<E> newNode = new Node<E>(obj);
// Link it to the nextItem.
newNode.next = nextItem; // Step 1
// Link nextItem to the new node.
nextItem.prev = newNode; // Step 2
// The new node is now the head.
head = newNode; // Step 3
} else if (nextItem == null) { // Insert at tail.
// Create a new node.
Node<E> newNode = new Node<E>(obj);
// Link the tail to the new node.
tail.next = newNode; // Step 1
// Link the new node to the tail.
newNode.prev = tail; // Step 2
// The new node is the new tail.
tail = newNode; // Step 3
} else { // Insert into the middle.
// Create a new node.
Node<E> newNode = new Node<E>(obj);
// Link it to nextItem.prev.
newNode.prev = nextItem.prev; // Step 1
nextItem.prev.next = newNode; // Step 2
// Link it to the nextItem.
newNode.next = nextItem; // Step 3
nextItem.prev = newNode; // Step 4
}
// Increase size and index and set lastItemReturned.
size++;
index++;
lastItemReturned = null;
} // End of method add.
} //end class KWListIter} // end of KWLinkedList class
我的问题 当我运行main方法时,我会陷入无限循环,我确实相信这与我的while循环情况有关。这是一件令人头疼的事情,我开始在其中抛出随机try-cat以帮助捕获抛出的异常以查看其打印内容。我需要休息一下,这是不得已的方法。
如果您可以指出明显的地方,那就太好了。谢谢。