这是我的java代码: -
import java.util.Scanner;
class Test
{
int maxSize;
int array[] = new int[maxSize];
Test(int maxSize)
{
this.maxSize = maxSize;
}
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
System.out.print("Enter size of Array:- ");
int maxSize = input.nextInt();
Test stack = new Test(maxSize);
System.out.println("Enter array element:- ");
for(int i=0; i<maxSize; i++)
{
stack.array[i] = input.nextInt();
}
for(int i=0; i<maxSize; i++)
{
System.out.print(stack.array[i]);
}
}
}
此代码提供错误Array Index Out Of Bounds
。如何将数组的大小设为maxSize
?
我尝试通过构造函数发送maxSize
,如上面的代码所示。但它不起作用。
我试过
class Test
{
int maxSize;
int array[];
Test(int maxSize)
{
this.maxSize = maxSize;
this.array[] = new int[maxSize];
:::::::::::::::::::::::::
它也不起作用。任何人都可以建议解决方案/改进,使其按预期工作。
答案 0 :(得分:6)
这一行:
int array[] = new int[maxSize];
在构造函数之前执行。
int maxSize;
effectivley意味着:
int maxSize = 0;
所以数组总是初始化为零长度数组。将您的代码更改为:
int maxSize;
int array[];
Test(int maxSize)
{
this.maxSize = maxSize;
array = new int[maxSize];
}
甚至不需要该类的 maxSize 成员,您甚至可以简单地执行此操作:
int array[];
Test(int maxSize)
{
array = new int[maxSize];
}
您总是可以获得数组的大小(假设数组已经初始化且不为空):
int length = array.length;
答案 1 :(得分:5)
在构造函数中初始化数组。语法是
Test(int maxSize) {
this.maxSize = maxSize;
this.array = new int[maxSize];
}
答案 2 :(得分:1)
您应该使用列表,例如矢量
import java.util.*;
class Test
{
//int maxSize;
public Vector<Integer> array;
Test()
{
//this.maxSize = maxSize;
array = new Vector<Integer>();
}
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
System.out.print("Enter size of Array:- ");
int maxSize = input.nextInt();
Test stack = new Test();
System.out.println("Enter array element:- ");
for(int i=0; i<maxSize; i++)
{
stack.array.add(input.nextInt());
}
for(int i : stack.array)
{
System.out.print(i);
}
}
}
答案 3 :(得分:1)
当您在声明array
处启动maxSize
时,最好在构造函数中启动数组:
int maxSize;
int[] array;
Test(int maxSize) {
this.maxSize = maxSize;
this.array = new int[maxSize];
}