首先,代码很长,但我只关心toString方法。我把所有东西都粘贴了,以防与之相关。
该代码应该检查输入的元素是否小于堆栈顶部的元素。我想好了那个部分。当我调用toString方法打印保存的输入时,它不会打印添加到堆栈中的第一个节点。但是,它会打印所有剩余的输入。例如,如果用户输入以下内容:
testing
test
te
t
What its currently outputing:
t te test
What it needs to output:
t te test testing
Main:
import java.util.*;
public class Stack {
public static void main(String args[]) {
int loopInt = 1;
PyramidStack<String> stringStack = new PyramidStack<String>();
PyramidStack<Integer> intStack = new PyramidStack<Integer>();
System.out
.println("This program will save some of the strings you enter. ");
System.out
.println("Can you predict which ones will be saved? (Enter nothing to quit.)");
Scanner sc = new Scanner(System.in); // Opens Scanner for keyboard input
try {
do {
System.out.print("Enter a String: ");
String input = sc.nextLine();
if (input.length() > 0) {
if (stringStack.size() == 0) {
intStack.push(input.length());
stringStack.push(input);
System.out.println("String Saved");
}
else if (input.length() < intStack.peek()) {
stringStack.push(input);
intStack.push(input.length());
System.out.println("String Saved");
}
else {
System.out.println("String NOT saved. Already saved "
+ intStack.countBefore(input.length())
+ " strings that should come before this one.");
}
} else {
System.out.println();
System.out.println(stringStack.toString());
System.out.println(intStack.toString());
loopInt--;
sc.close();
}
} while (loopInt > 0);
} catch (NullPointerException e) {
System.out.println("No strings have been entered. Ending the program.");
}
}
}
金字塔堆叠法:
import java.util.*;
import java.lang.Comparable;
public class PyramidStack<E extends Comparable<E>> extends Stack<E> {
@Override
public void push(E item) throws IllegalArgumentException {
if (super.size == 0) {
super.push(item);
}
else if(item.compareTo(super.peek()) <= 0) {
super.push(item);
}
else {
System.out.println("String NOT saved. " + countBefore(item) + " strings that should come before this one.");
}
}
@Override
public String toString() {
Node<E> node;
node = this.top;
String s = "";
while(node.getNext() != null){
s += node.getData() + " ";
node = node.getNext();
}
return s;
}
public int countBefore(E item) {
Node<E> node;
node = this.top;
int i = 0;
while(node.getNext() != null){
if(item.compareTo(super.peek()) <= 0) {
node = node.getNext();
}
else{
i++;
node = node.getNext();
}
}
return i;
}
}
Stack方法和Node方法。
while(node.getNext() != null){
s += node.getData() + " ";
node = node.getNext();
}
这是您缺少的打印最后一个数据的地方。。您正在检查node.getnext()为null。。所以它跳过最后一个对象,不打印。。您的状况应该是node != null
或
循环结束后有此s += node.getData()
——由于节点不为null,因此不会出现null指针异常。。就像它检查node.getnext()一样
希望它能帮助