簡體   English   中英

如何將變量從main方法類轉移到另一個類?

[英]How to transfer a variable from main method class to another class?

好的...在我的主類中,我要求用戶輸入一個輸入int值。 現在我需要將這個值帶到另一個類來進行編碼。 怎么樣?

主類代碼:

neededValue = keyboard.nextInt();

object.methodName(xxxx, yyyy):

來自不同類中的不同方法的代碼:

public void methodName(double xxxx, int yyyy) {

        int index;

        for (index = 0; index < array.length; index++) {
            xxxx = array[index].xxxx;
            if (xxxx > **neededValue**) {
                //some more code

            }

        }
    }

讓我們說用戶輸入是4,如何將“4”轉移到其他類?

您需要傳遞neededValue作為參數

neededValue = keyboard.nextInt();   
object.methodName(xxxx, yyyy,neededValue):

然后在methodName函數中

public void methodName(double xxxx, int yyyy, int neededValue) {

    int index;

    for (index = 0; index < array.length; index++) {
        xxxx = array[index].xxxx;
        if (xxxx > **neededValue**) {
            //some more code
        }
    }
}

希望它有所幫助。

從主要:

neededValue = keyboard.nextInt();

object.methodName(xxxx, yyyy, neededValue):

來自班級:

public void methodName(double xxxx, int yyyy, int neededValue){
    int index;

    for (index = 0; index < array.length; index++) {
        xxxx = array[index].xxxx;
        if (xxxx > **neededValue**) {
            //some more code
        }
    }
}

將參數添加到另一個類方法並從主類傳遞值。如下所示:

class A{
...
neededValue = keyboard.nextInt();

DifferentClass object = new DifferentClass();
object.methodName(xxxx, yyyy, neededValue):
...
}

class DifferentClass{
public void methodName(double xxxx, int yyyy, int neededValue) {
...
}
}
  1. 您可以將nextValue變量直接傳遞給方法,例如:

object.methodName(xxxx, yyyy, nextValue)

  1. 或者你可以在對象的類A中聲明一個int變量:

    int someValue;

並通過構造函數或setter設置它

object = new A(nextValue);
or object.setNextValue(nextValue)

然后,你的invoke object.methodName(xxxx, yyyy)將使用對象內的'someValue'字段

有多種方法,下面列出的很少,

i)在您的方法中創建參數(在其他解決方案中解釋)。

ii)使用類中的get / set方法在類中創建變量(在其他解決方案中進行了解釋)。

iii)在你的班級中創建一個靜態變量(如下所述)

您可以在班級中擁有靜態變量,

private static int neededValue;

在您的主要內容中,您可以為其分配值。

ClassName.neededValue = keyboard.nextInt();

object.methodName(xxxx, yyyy):

你可以直接在你的類方法中使用,

public void methodName(double xxxx, int yyyy){
int index;

for (index = 0; index < array.length; index++) {
    xxxx = array[index].xxxx;
    if (xxxx > ClassName.neededValue) {
        //some more code
    }
 }
}

免責聲明:在使用之前了解有關靜態關鍵字的更多信息。

暫無
暫無

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

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