Java 以另一种方法访问数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29551268/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 08:12:01  来源:igfitidea点击:

Accessing an array in another method

javaarraysvariablespublic

提问by Michael Miller

I am trying to access an array in a separate method that it is initialized in.

我试图在一个单独的方法中访问一个数组,它是在其中初始化的。

public void initializeArray()
{                
    String sentences[] = new String[5];

    for(int i=0; i<5; i++)
    { 
        sentences[i] = i+1;
    }
}

public void printArray()
{
    for(int i=0; i<5; i++)
    {
        System.out.println(sentences[i]);
    }
}

I know that I could do this in one for loop, but can someone explain how I could print the array this way? I need to access the sentences array in a separate method that it is initialized in. I tried to make an instance of the array at the top of the program but it gives me an error saying "Local variable hides a field".

我知道我可以在一个 for 循环中执行此操作,但是有人可以解释我如何以这种方式打印数组吗?我需要在一个单独的方法中访问句子数组,它被初始化。我试图在程序的顶部创建一个数组的实例,但它给了我一个错误,说“局部变量隐藏了一个字段”。

回答by MadConan

Change the signature of your printArraymethod to be

将您的printArray方法的签名更改为

public void printArray(String[] sentences){...}

So you have

所以你有了

public void initializeArray(){
   int arraySize = 5;
   String[] sentences = new String[arraySize];
   for(int i=0; i<arraySize; i++){
        sentences[i] = new String(i+1);
   }
   printArray(sentences);
}

回答by Gentatsu

Make sentences a global variable or parameters to both functions.

使句子成为两个函数的全局变量或参数。

回答by Gentatsu

I tried to make an instance of the array at the top of the program but it gives me an error saying "Local variable hides a field".

我试图在程序顶部创建一个数组实例,但它给了我一个错误,说“局部变量隐藏了一个字段”。

You already have a instance variable, so remove the local variable within method:

您已经有一个实例变量,因此删除方法中的局部变量:

public void initializeArray()
{                
    //String Sentences[] = new String[5];
    ...
}

Also don't use magic numbers like you did in for-loop:

也不要像在 for 循环中那样使用幻数:

for(int i=0; i<5; i++)//use `sentences.length` instead of `5`

回答by dasblinkenlight

There are two ways to access the same array from two methods:

有两种方法可以从两种方法访问同一个数组:

  • Access the array through an instance variable of array type, or
  • Pass the array to methods as a parameter.
  • 通过数组类型的实例变量访问数组,或
  • 将数组作为参数传递给方法。

The first approach looks like this:

第一种方法如下所示:

class TestInstanceVar {
    private String[] sentences = new String[5];
    public static void main(String[] args) {
        TestInstanceVar obj = new TestInstanceVar();
        obj.initializeArray();
        obj.printArray();
    }
    public void initializeArray() {
        ...
    }
    public void printArray() {
        ...
    }
}

Here, the methods access sentencesas an instance variable, which is shared across all methods running on the same instance.

在这里,方法sentences作为实例变量访问,该变量在同一实例上运行的所有方法之间共享。

The second approach looks like this:

第二种方法如下所示:

class TestPassArray {
    public static void main(String[] args) {
        private String[] sentences = new String[5];
        initializeArray(sentences);
        printArray(sentences);
    }
    public static void initializeArray(String[] sentences) {
        ...
    }
    public static void printArray(String[] sentences) {
        ...
    }
}

Here the array is created in the mainmethod, and is passed explicitly as a parameter to the initialization and printing methods. Note that the methods are marked static, and accessed without creating an object.

这里数组是在main方法中创建的,并作为参数显式传递给初始化和打印方法。请注意,这些方法被标记为static,并且无需创建对象即可访问。

回答by Scary Wombat

Have your initializeArrayreturn an Array as in

让你initializeArray返回一个数组

public String[] initializeArray () {

   ...
   return sentences;
}

Change yourprintArrayto

改变你printArray

public void printArray (String [] arr) {
   ...
   System.out.println(arr[i]);
}

Imagine a main method like

想象一个主要的方法,比如

String myArr [] = initializeArray  ();
printArray (myArr);

回答by DWright

The following should work:

以下应该工作:

class MyClass
{

    private String sentences[] = new String[5];

    public void initializeArray()
    {                
        for(int i=0; i<5; i++)
        { 
            sentences[i] = i+1;
        }
    }

    public void printArray()
    {
        for(int i=0; i<5; i++)
        {
            System.out.println(sentences[i]);
        }
    }
}

回答by gran_profaci

The printArraymethod knows nothing of sentences right?

printArray方法对句子一无所知,对吗?

Java is pass by value and requires you to literally give the value of a piece of data to a method in order for the method to crunch on it. Global values are basically values that are known to every object.

Java 是按值传递的,它要求您按字面意思将一段数据的值赋予一个方法,以便该方法对其进行处理。全局值基本上是每个对象都知道的值。

Thus, you need something that will tell both initializeArrayand printArraythat there is this piece of data sentences that should be worked on.

因此,您需要一些可以告诉两者的东西,initializeArray并且printArray应该处理这段数据语句。

// A Calling Function
public void initializeAndPrintStringArray
{
    // Get the initialized Sentences Array
    String[] sentences = initializeArray();

    // Print this Initialized Array
    printArray(sentences)
}

// For doing this, you need to change the definitions of your methods

public String[] initializeArray()
{                
    String[] sentences = new String[5]; // You have a spelling mistake here

    for(int i=0; i<5; i++)
    { 
        sentences[i] = i+1;
    }
    return sentences
}

public void printArray(String[] sentences)
{
    // Don't assume the length will always be 5 or something you know beforehand.
    for(int i=0; i<sentences.length; i++) 
    {
        System.out.println(sentences[i]);
    }
}

回答by Local Maximum

You are declaring the variable sentences[]inside the method initializeArray(). Because of this, it doesn't exist outside of this method. As soon as the method finishes, it disapears. Other methods can't use the variable.

您在initializeArray()方法中声明了变量句子 []。因此,它在此方法之外不存在。该方法一完成,它就会消失。其他方法不能使用该变量。

You should declare the variable outside the method, like this:

您应该在方法之外声明变量,如下所示:

public class Example {

    static String sentences[] = new String[5];;

    public static void main(String[] args) {
        initializeArray();
        printArray();
    }

    public static void initializeArray() {
        for (int i = 0; i < 5; i++) {
            sentences[i] = "" + (i + 1);
        }
    }

    public static void printArray() {
        for (int i = 0; i < 5; i++) {
            System.out.println(sentences[i]);
        }
    }
}

That way, you can use it anywhere in this class. If you want to use it somewhere else, too, add the keyword public before it.

这样,你就可以在这个类的任何地方使用它。如果您也想在其他地方使用它,请在它之前添加关键字 public。