簡體   English   中英

在 java 中使用 static 變量

[英]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 中,如果塊語句( ifelseforwhile等)后面沒有大括號,它只將下一行視為塊的內容。

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM