Reputation: 19
I have this snippet of code and the output is coming out to be 4x^3 + 3x^2 + -5x^0 + 3x^5 + 4x^4 + 1x^3 + -4x^2 + 4x^1 + 2x^1 + -5x^0 + 3x^2 + 4x^3 + -4x^0 + 4x^3 + 5x^4 +
.
Can someone please help get rid of the last +
at the end?
Here's the code:
public static void Iterate(PolyDS result) {
NodeClass node = result.getFirstNode();
while(node!= null) {
System.out.print(node.getCoeff() + "x" + "^" + node.getExpo() + " + ");
node = node.getNext();
}
}
Upvotes: 0
Views: 84
Reputation: 521194
One option is to peek ahead to the next value of node
in the loop, and to print a connecting +
only when the next node is not null
:
NodeClass node = result.getFirstNode();
while (node != null) {
String msg = node.getCoeff() + "x" + "^" + node.getExpo();
node = node.getNext();
msg += node != null ? " + " : "";
System.out.print(msg);
}
Upvotes: 1
Reputation: 7917
Change
System.out.print(node.getCoeff() + "x" + "^" + node.getExpo() + " + ");
node = node.getNext();
to
System.out.print(node.getCoeff() + "x" + "^" + node.getExpo());
if(node.hasNext()) System.out.print(" + ");
node = node.getNext();
Ideally you should use something like while(node.hasNext())
.
Upvotes: 1