我想在java中声明一个空数组,然后我想更新它,但代码不工作……
public class JavaConversion
{
public static void main(String args[])
{
int array[]={};
int number = 5, i = 0,j = 0;
while (i<4) {
array[i]=number;
i=i+1;
}
while (j<4) {
System.out.println(array[j]);
}
}
}发布于 2016-01-19 00:22:45
您正在创建一个长度为零的数组(没有可放入任何内容的槽)
int array[]={/*nothing in here = array with no elements*/};然后尝试为数组元素赋值(您没有,因为没有槽)
array[i] = number; //array[i] = element i in the array of length 0您需要定义一个更大的数组来满足您的需求
int array[] = new int[4]; //Create an array with 4 elements [0],[1],[2] and [3] each containing an int value发布于 2016-01-19 00:27:27
您的代码可以很好地编译。但是,您的数组初始化行是错误的:
int array[]={};这样做的目的是声明一个大小等于括号中元素数量的数组。由于括号中什么都没有,所以数组的大小是0-这使得数组完全无用,因为现在它不能存储任何东西。
相反,您可以直接在原始行中初始化数组:
int array[] = { 5, 5, 5, 5 };或者您可以声明大小,然后填充它:
int array[] = new int[4];
// ...while loop如果您事先不知道数组的大小(例如,如果您正在读取文件并存储内容),则应该改用ArrayList,因为这是一个随着添加更多元素而动态增长的数组(用外行术语来说)。
发布于 2016-01-19 00:19:23
您需要为数组指定一个大小:
public static void main(String args[])
{
int array[] = new int[4];
int number = 5, i = 0,j = 0;
while (i<4){
array[i]=number;
i=i+1;
}
while (j<4){
System.out.println(array[j]);
j++;
}
}https://stackoverflow.com/questions/34859322
复制相似问题