簡體   English   中英

如何從公共static void main到另一個類調用變量?

[英]How do I call a variable from the public static void main to another class?

我無所不在,一直到處尋找。 我得到了這個代碼

public class Main
{
public static void main(String args[])
{
  int target = (int) (Math.random() * 1000);

    System.out.println("The number is " + target);

}

}

他們要我創建一個使用目標的類Finder,並在for語句中使用它。 我的問題是我不知道如何從此代碼中提取目標。 我是一名學生,我們正在使用的書沒有幫助。 我嘗試用

numberSearch = Main.target
numberSearch = Main.main.target
numberSearch = Main.main() 

還有很多其他

您不能在方法外部訪問局部變量

您說過“創建一個帶有目標的Finder類”,這意味着Finder類應該在構造函數或執行查找的方法上接受目標值作為參數。

// Using constructor
public class Finder {
    private int target;
    public Finder(int target) {
        this.target = target;
    }
    public void find() {
        // perform find of 'this.target' here
    }
}

// On find method
public class Finder {
    public void find(int target) {
        // perform find of 'target' here
    }
}

首先,讓我們使用選項卡訂購代碼

public class Main
{

    public static void main(String args[])
    {   
        int target = (int) (Math.random() * 1000);

        System.out.println("The number is " + target);
    }

}

現在,您要做的就是創建一個您要在學校使用的班級的對象(查找器)。 讓我們將此對象的標識符設為“ obj”。

public class Main
{

    public static void main(String args[])
    {   
        Finder obj = new Finder();
        int target = (int) (Math.random() * 1000);

        System.out.println("The number is " + target);
    }

}

現在,我們已經完成了這一步,您必須在Finder類中創建一個接受整數的方法(因此它可以接受您稱為target的變量,因為它本身就是一個int)。 在for循環中使用變量target的此類方法的示例為:

public void forLoopMethod(int target)
{
    //Some sort of for loop involving the int target goes here:
    for()
    {

    }
}

然后在名為Main的類中簡單地調用forLoopMethod方法

public class Main
{

    public static void main(String args[])
    {   
        Finder obj = new Finder();
        int target = (int) (Math.random() * 1000);

        obj.forLoopMethod(target);
        System.out.println("The number is " + target);
    }

}

您的問題是您試圖在單獨的類中查找局部變量。 變量可以在main()之類的方法外部設置,如果它們是公共變量,則可以由另一個類輕松訪問。

在main()函數外部,在Main類內部,您將放置numberSearch變量。 然后在Finder中,您可以通過獲取Main.numberSearch的值來訪問numberSearch。

請注意,如果您的教授希望您使用私有變量,則需要使用getter和setter。

/*How I tested the code*/
public class Main {
    public static int numberSearch;
    public static void main(String args[]) {
        int target = (int) (Math.random() * 1000);
        numberSearch = target;
        Finder.getResult();
    }
}

/*in a separate file*/
public class Finder {

    public static void getResult() {
        int t = Main.numberSearch;
        System.out.println(t);
    }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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