[英]Share variable between methods in Java
I'm new in Java and I have little problem. 我是Java新手,没什么问题。 I want to make array in one method and display in length in other.
我想用一种方法制作数组,而用另一种方法显示长度。 I know how to to both in one method:
我知道如何在一种方法中同时做到:
class Test
{
public void create()
{
Scanner in = new Scanner(System.in);
System.out.println("Number of elements: ");
int n=in.nextInt();
int arr[]=new int[n];
System.out.println("Number of elements: " + arr.length);
}
}
But how can I do something like this? 但是我该怎么做呢?
class Test
{
public void create()
{
Scanner in = new Scanner(System.in);
System.out.println("Number of elements: ");
int n=in.nextInt();
int arr[]=new int[n];
}
public void display()
{
System.out.println("Wielkosc tablicy: " + arr.length);
}
}
Make arr
a private instance variable of your class, so that it is accessible from any method: 将
arr
设为您的类的私有实例变量,以便可以通过任何方法对其进行访问:
class Test
{
private int[] arr;
public void create()
{
Scanner in = new Scanner(System.in);
System.out.println("Number of elements: ");
int n=in.nextInt();
arr=new int[n];
}
public void display()
{
System.out.println("Wielkosc tablicy: " + arr.length);
}
}
If the array is only expected to exist within the lifetime of a call to create
I'd recommend making display
private. 如果阵列只希望呼叫的生命周期内存在
create
我建议你做display
私人。 Then updating the signature of display to take an int[] as an argument 然后更新显示的签名以int []作为参数
class Test {
public void create() {
Scanner in = new Scanner(System.in);
System.out.println("Number of elements: ");
int n=in.nextInt();
int arr[]=new int[n];
display(arr);
}
private void display(int[] arr) {
System.out.println("Wielkosc tablicy: " + arr.length);
}
}
If the int[] is to live for longer than just the call to create
then you should make the int[] a field on on Test
as mentioned in the answer by @lodo 如果int []的生存期要比
create
调用的生存期长,则应将int []设置为Test
上的字段,如@lodo的答案中所述
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.