问题
Just trying to understand the basics of how this should work. Here is my code.---------------------------> This is my main class.
public class Driver
{
public static void main(String[] args)
{
//create new instance of the ArrayLab class with parameter of 10
ArrayLab array = new ArrayLab(10);
//search for 2
array.search(2);
}
}
The class ArrayLab has a method assigned to it called search with parameter of (2). So far this is what I have.
import java.util.Arrays;
public class ArrayLab
{
//array instance variable
int[] array1 = new int[10];
//array constructor
public ArrayLab(int integer)
{
//class parameter = 10
int[] array1 = new int[integer];
}
//method
public void search(int integer)
{
int[] array1= new int[]{integer};
System.out.println(Arrays.toString(array1));
}
}
So the big question is what am I doing right? or wrong? I realize this is probably pretty basic, just struggling to understand what is happening inside the code. Thanks :)
回答1:
Your Driver class is good.
So, lets take one line at a time
int[] array1 = new int[10];
Okay, you made a public int array of size 10, more precisely [0, 0, 0, 0, 0, 0, 0, 0, 0, 0].
public ArrayLab(int integer)
{
int[] array1 = new int[integer];
}
This is called a constructor. You are passing in integer, and making a new array called array1 which is local to this scope, therefore different than the one before. This array1 contains integer-many zeros.
To use and initialize the previous array1, change your code up to here to this
int[] array1;
public ArrayLab(int integer)
{
this.array1 = new int[integer];
}
Next,
public void search(int integer)
{
int[] array1= new int[]{integer};
}
}
This, again, creates a new array, but only one value. So say integer was 2, then [2].
回答2:
I don't know what the purpose of your ArrayLab class is , but here are some problems
In the constructor you are initializing a local
array1not your instance variable .searchmethod is doing nothing but again initializing a localarray1.
回答3:
Alright, so whats happening is in your class Driver your creating a object of your class ArrayLab. You send this class a constructor which creates a local variable array1. Your search class initializing another local array1 this is what i would do for your ArrayLab class
import java.util.Arrays;
public class ArrayLab
{
int[] array1;
//array constructor
public ArrayLab(int integer)
{
this.array1 = new int[integer];
}
//method
public void search(int integer)
{
System.out.println(array1[integer]);
}
}
来源:https://stackoverflow.com/questions/33272636/how-to-access-parameters-in-a-method-for-an-array-java