使用方法访问数组 [英] Accessing arrays with methods
问题描述
大家好我刚刚开始学习Java,我想知道如何从另一个方法访问一个方法中声明的数组?
设计如下所示:
Hi guys i'm just starting to learn Java, and I wondering how can I access an array that was declared in a method from another method? The design look like this:
public class Arrays{
int arraysize = 2;
public void initializeArray(){
float array[] = new float[arraySize]; // Declare array
}
public void accessArray(){
// I want to access the array from this method.
}
}
推荐答案
了解java中的变量范围。这是我在快速Google搜索中找到的链接。 http://www.java-made-easy.com/variable-scope.html
Read about scope of variables in java. This is link I could find on quick Google search. http://www.java-made-easy.com/variable-scope.html
您可以在类级别声明数组,然后可以在所有方法中访问它。
You can declare the array at class level then it is accessible in all methods.
public class Arrays {
int arraysize = 2;
private float[] array = null;
public void initializeArray() {
array = new float[arraySize]; // Declare array
}
public void accessArray() {
// access array here.
}
}
或者您可以在方法中传递变量。
Or You can pass the variables in method.
public class Arrays {
int arraysize = 2;
public void initializeArray() {
float[] array = new float[arraySize]; // Declare array
accessArray(array);
}
public void accessArray(float[] array) {
// access array here.
}
}
鉴于信息量,我有疑问,方法1似乎优于2。
Given the amount of information, I have from question, approach 1 seems better than 2.
这篇关于使用方法访问数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!