[英]Using a static variable in java
我试图打印链接列表实现的堆栈元素。
但是要按堆栈本身的顺序打印,我需要 java 中的 static 变量。
public void display()
{
<STATIC> <here I need> LinkedListImp temp = this;
while(temp.next!=null)
{
temp=temp.next;
display();
}
System.out.println("\n\t"+ temp.element +"\n");;
}
但是在这样声明时,我收到了一个错误。
我已经在接口概念中实现了 display() 。 因此我不能有显示(LinkedListImp temp)。
interface StackMethods
{
int pop();
void push(int numberint);
void display();
}
例如,如果堆栈的元素是 1 然后 2 然后 3。我不希望 output 为 1 2 3 或 1(换行)2(换行)3。
相反,我想要 3 (newline) 2 (newline) 1 (尽管不需要演示真正的堆栈)
还有其他方法可以实现吗?
如果您希望temp
的值不依赖于display()
的父 class ( LinkedListImp
?)的实例,那么您需要一个 static ZA2F2ED4F8EBC2CBB4C21A29DC40AB61Z 变量。 在 Java 中, static
关键字标记了一个变量,该变量属于整个 class,而不是单个实例。 Java 中的 Static 创建了一个也称为“类变量”的变量。 根据定义,class 变量不能是本地变量。 要了解有关 static 变量的更多信息,请参阅文档要说的内容或查看答案中有规范的 StackOverflow 问题。
但看起来你想要做的是使用一个类的实例,这意味着你不想要一个 static 变量。 您绝对希望该值与 class 相关联。
但是,要使其正常工作,您需要在 while 循环中的两个语句周围加上大括号。 否则,您将获得一个循环遍历链表的所有元素并仅打印最后一个元素的程序。 这是因为在 Java 中,如果块语句( if
、 else
、 for
、 while
等)后面没有大括号,它只将下一行视为块的内容。
public void display()
{
LinkedListImp temp = this;
while(temp.next!=null)
{
System.out.println("\n\t"+ temp.element +"\n");
temp=temp.next;
}
}
要使用循环反转此处的顺序,我将使用StringBuilder并构建一个字符串。
public void display()
{
LinkedListImp temp = this;
StringBuilder result = new StringBuilder();
while(temp.next!=null)
{
result.insert(0, "\n\t"+ temp.element +"\n"); // put the result at the front
temp=temp.next;
}
System.out.println(result.toString());
}
根据您的编辑,您添加了对该方法的递归调用,但循环不需要这样做。 如果您正在执行递归,请删除循环。 在这种情况下,递归充当循环。 在这种情况下,只需在调用 display 后打印出该项目,并使用下一个项目进行反向排序,或者在标准订单之前打印出来。
public display() {
doDisplay(this);
}
private void doDisplay(LinkedListImpl item) {
if(item.next) // implicit != null
{
doDisplay(item.next);
}
System.out.println("\n\t" + temp.element + "\n"); // this line goes before
// the if statement for
// regular ordering
}
Java 无法在 C 之类的函数中将变量声明为 static。 我不明白为什么您认为为此需要一个 static 变量...
static
变量的声明与使用 static 关键字的普通实例变量一样。 在方法中声明它们是非法的。 另外,为什么不直接使用this
而不是将其分配给变量呢?
要以相反的顺序打印您的列表,您可以使用辅助方法:
public void display() {
displayHelper(this);
}
private void displayHelper(LinkedListImp temp) {
if (temp.next != null)
displayInternal(temp.next);
System.out.println("\n\t"+ temp.element +"\n");;
}
递归工作正常。 我们甚至不需要辅助方法。
public void display()
{
// Displays in reverse order. For forwards order, do it the other way around.
if (next != null) { next.display(); }
System.out.println("\n\t"+ element +"\n");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.