整数数组访问-Java
我有一个大小为50的整数数组。 因此,正如您所知,最初这个数组的元素值都是0。 我需要做的是: 如果数组=[12,10,0,0,…0 ],for循环只需要考虑非零元素,那么循环应该只执行两次…一次为12次,下一次为10次。 类似地,如果数组为=[0,0,0,…..0],则不应执行for循环,因为所有元素都为零。 如果数组为[12,10,5,0,17,8,0,0,…,0],则应对前6个元素执行for循环,即使其中一个内部元素为零 这是我的。这给了我一个IndexOutOfBoundsException。请帮忙。 还有,有没有什么方法可以动态增加int数组的大小,而不是将其设置为50,然后在循环中使用它?谢谢您的帮助整数数组访问-Java,java,arrays,for-loop,int,Java,Arrays,For Loop,Int,我有一个大小为50的整数数组。 因此,正如您所知,最初这个数组的元素值都是0。 我需要做的是: 如果数组=[12,10,0,0,…0 ],for循环只需要考虑非零元素,那么循环应该只执行两次…一次为12次,下一次为10次。 类似地,如果数组为=[0,0,0,…..0],则不应执行for循环,因为所有元素都为零。 如果数组为[12,10,5,0,17,8,0,0,…,0],则应对前6个元素执行for循环,即使其中一个内部元素为零 这是我的。这给了我一个IndexOutOfBoundsExcepti
int[] myArray = new int[50];
int cntr = 0;
int x = getXvalue();
int y = getYvalue();
if (x>y){
myArray[cntr] = x;
cntr++;
}
for (int p=0; p<= myArray.length && myArray[p]!=0 ; p++){
//execute other methods..
}
//解决方案:
我使用了ArrayList而不是int数组来动态增加数组的大小
ArrayList<Integer> myArray = new ArrayList<Integer>();
To set the value of the elements-
myArray.add(cntr, x); // add(index location, value)
这是有问题的:
for (int p=0; p<= myArray[cntr].length && myArray[p]!=0 ; p++){
这是有问题的:
for (int p=0; p<= myArray[cntr].length && myArray[p]!=0 ; p++){
更清洁的方法是:
解决此类问题最方便的方法是使用适当的集合。对于这个示例,您可以考虑使用ARARYLIST.
优点是不必预先初始化给定大小的列表。如有必要,它还将调整大小
另一个优点是,您不必关心填充空元素以及处理列表末尾的空元素
具体问题是:
它必须是myArray.length
您还可以使用从0..50进行迭代,更简洁的方法是:
解决此类问题最方便的方法是使用适当的集合。对于这个示例,您可以考虑使用ARARYLIST.
优点是不必预先初始化给定大小的列表。如有必要,它还将调整大小
另一个优点是,您不必关心填充空元素以及处理列表末尾的空元素
具体问题是:
它必须是myArray.length
您还可以从0..50使用
这一行甚至不应该编译。你可能是指myArray.length?另一个错误是:使用
这一行甚至不应该编译。你可能是指myArray.length?另一个错误:使用这将有助于解决您的问题
int len = myArray.length;
for (int p=0; p < len; p++){
cntr++;
while(myArray[p]==0){
if((p+1) != len) p++;
}
System.out.println(myArray[p]);
System.out.println("cntr: " + cntr++);
//execute other methods..
}
但是更好的处理数组的方法是使用集合ArrayList。这将有助于解决您的问题
int len = myArray.length;
for (int p=0; p < len; p++){
cntr++;
while(myArray[p]==0){
if((p+1) != len) p++;
}
System.out.println(myArray[p]);
System.out.println("cntr: " + cntr++);
//execute other methods..
}
但是处理数组的更好方法是使用集合ARAYLIST.
< P>为什么不考虑在for循环中添加一个继续语句,比如这个for (int p=0; p<= myArray.length ; p++)
{
if( myArray[p]==0){
continue;
}
//execute other methods..
}
为什么不考虑在for循环中添加一个继续语句,比如这个< /p>
for (int p=0; p<= myArray.length ; p++)
{
if( myArray[p]==0){
continue;
}
//execute other methods..
}
考虑使用ARARYLIST。它使用简单,可以动态调整大小。哪一行抛出异常?@Arjan-for循环使用ArrayList抛出一个ExceptionConsider。它使用简单,可以动态调整大小。哪一行抛出异常?@Arjan-for循环抛出异常项..那是一个输入错误…我是说myArray.length.Yes..那是一个输入错误…我是说myArray.length.Thx!我已经按照你的建议使用了ArrayList。我的帖子中包含了解决方案:谢谢!我已经按照你的建议使用了ArrayList。我的帖子中包含了解决方案:
int len = myArray.length;
for (int p=0; p < len; p++){
cntr++;
while(myArray[p]==0){
if((p+1) != len) p++;
}
System.out.println(myArray[p]);
System.out.println("cntr: " + cntr++);
//execute other methods..
}
for (int p=0; p<= myArray.length ; p++)
{
if( myArray[p]==0){
continue;
}
//execute other methods..
}