为什么在 java 数组中传递给方法的构造函数是非法的?
Why is this illegal in java array passed into constructor to a method?
我想创建一个让我初始化为数组的对象
arraysort test_array = new arraysort.(array_to_be_input);
然后它将有几种方法,例如排序删除重复项等。但我希望数组在传递到 class 后立即进行排序。
刚刚写了下面的代码,不明白为什么会出错
public class arraysort{
int[] a;
/* array is input when the object is created */
arraysort(int[] a){
this.a=a;
}
/*array is put into the sort method*/
public int[] sortit(a){
int i = 0;
while(i<array.length){
i++;
}
return a;
}
public static void main(String[] args) {
}
}
您的 sortit
方法有几个错误。
您忘记声明参数并尝试访问不存在的数组(array.length)。按以下方式尝试:
public int[] sortit(int[] a){ // <--- declare your parameters
int i = 0;
while(i < a.length){ //<--- access passed parameters
//whatever you want to do
}
return a;
}
->你 while 条件有错别字:-
将此 while(i<array.length)
更改为此 while(i<a.length)
->你的main()
方法是空的,在main方法中调用你的代码来执行它。
public static void main(String[] args) {
int[] arr=new int[3];
arr[0]=1;
arr[1]=4;
arr[2]=2;
arraysort as=new arraysort(arr);
as.sortit(arr);
}
其他一些要强调的要点是:-
-> class 名称以大写开头:- class ArraySort
->您的 sortit(a)
方法接受输入 a ,但它不是必需的,因为它是一个 class 变量,可以直接在方法中访问。
-> 您的 sortit(a)
方法不会对 a
执行任何 sorting/computation,而只是 returns 它。
我想创建一个让我初始化为数组的对象
arraysort test_array = new arraysort.(array_to_be_input);
然后它将有几种方法,例如排序删除重复项等。但我希望数组在传递到 class 后立即进行排序。
刚刚写了下面的代码,不明白为什么会出错
public class arraysort{
int[] a;
/* array is input when the object is created */
arraysort(int[] a){
this.a=a;
}
/*array is put into the sort method*/
public int[] sortit(a){
int i = 0;
while(i<array.length){
i++;
}
return a;
}
public static void main(String[] args) {
}
}
您的 sortit
方法有几个错误。
您忘记声明参数并尝试访问不存在的数组(array.length)。按以下方式尝试:
public int[] sortit(int[] a){ // <--- declare your parameters
int i = 0;
while(i < a.length){ //<--- access passed parameters
//whatever you want to do
}
return a;
}
->你 while 条件有错别字:-
将此 while(i<array.length)
更改为此 while(i<a.length)
->你的main()
方法是空的,在main方法中调用你的代码来执行它。
public static void main(String[] args) {
int[] arr=new int[3];
arr[0]=1;
arr[1]=4;
arr[2]=2;
arraysort as=new arraysort(arr);
as.sortit(arr);
}
其他一些要强调的要点是:-
-> class 名称以大写开头:- class ArraySort
->您的 sortit(a)
方法接受输入 a ,但它不是必需的,因为它是一个 class 变量,可以直接在方法中访问。
-> 您的 sortit(a)
方法不会对 a
执行任何 sorting/computation,而只是 returns 它。