在Java中从数组提取时出错
我写了那种代码在Java中从数组提取时出错,java,arrays,indexoutofboundsexception,Java,Arrays,Indexoutofboundsexception,我写了那种代码 int[] count = new int[10]; int i = count.length; int position = -1; int num = kb.nextInt(); while(i > 0) { if(count[i] == num) { position = i; break; } i--; } 但是我得到了jav
int[] count = new int[10];
int i = count.length;
int position = -1;
int num = kb.nextInt();
while(i > 0)
{
if(count[i] == num)
{
position = i;
break;
}
i--;
}
但是我得到了java.lang.ArrayIndexOutOfBoundsException
错误
目的是在数组中查找用户选择的最后一个数字。在第一次迭代中,您可以访问
count[count.length]
数组是基于零的,因此应该初始化
int i = count.length-1;
在第一次迭代中,您可以访问
count[count.length]
数组是基于零的,因此应该初始化
int i = count.length-1;
设置
i=count.length代码>。在java中数组是从0索引的,因此count[count.length]
超出了范围。数组a
中的最后一个有效索引是a.length-1
您设置的i=count.length代码>。在java中数组是从0索引的,因此count[count.length]
超出了范围。数组a
中的最后一个有效索引是a.length-1
这是错误的:
int i = count.length;
...
while(i > 0)
{
if(count[i] == num)//count[count.length] is out of bound. Maximum index is count.length-1
试一试
这是错误的:
int i = count.length;
...
while(i > 0)
{
if(count[i] == num)//count[count.length] is out of bound. Maximum index is count.length-1
试一试
第一个i值为10,即数组的大小+1-->导致IndexOutOfBoundException
迭代时,始终将1减为您想要的值:要访问“first”值,请选择索引0,对于“last”,索引为9;) 第一个i值为10,即数组的大小+1-->导致IndexOutOfBoundException
迭代时,始终将1减为您想要的值:要访问“first”值,请选择索引0,对于“last”,索引为9;) 您的数组“count”的长度为10。
Java数组以索引0开头。因此,最后一个元素的长度为-1=9
从i=count.length=10开始
计数[10]将抛出该异常
快速解决您的问题:
int i = count.length - 1;
数组“count”的长度为10。
Java数组以索引0开头。因此,最后一个元素的长度为-1=9
从i=count.length=10开始
计数[10]将抛出该异常
快速解决您的问题:
int i = count.length - 1;
这是正确的:
int[] count = new int[10];
int i = count.length;
int position = -1;
int num = kb.nextInt();
while(i > 0)
{
i--;
System.out.println(i);
if(count[i] == num)
{
position = i;
break;
}
}
该数组由10个项目组成,从0开始,到9结束。它将是正确的:
int[] count = new int[10];
int i = count.length;
int position = -1;
int num = kb.nextInt();
while(i > 0)
{
i--;
System.out.println(i);
if(count[i] == num)
{
position = i;
break;
}
}
public class arra {
public static void main(String[] args) {
Scanner kb=new Scanner(System.in);
int[] count = new int[10];
int i = count.length-1;
int position = -1;
int num = kb.nextInt();
while(i > 0)
{
if(count[i] == num)
{
position = i;
break;
}
i--;
}
}
}
数组由10项组成,从0开始到9结束读取错误并找出它有多困难?您有一个从[0,9]开始运行的数组,但您对我的值超出了该范围。谢谢大家的帮助,很抱歉用这么愚蠢的问题打扰您。再次感谢您的解释。最简单的也是最难的。作为旁注,您可能应该使用for
循环。读取错误并找出它有多困难?您有一个从[0,9]开始运行的数组,但您对我的值超出了该范围。谢谢大家的帮助,很抱歉用这么愚蠢的问题打扰您。再次感谢您的解释。最简单的也是最难的。作为旁注,您可能应该使用for
循环。
public class arra {
public static void main(String[] args) {
Scanner kb=new Scanner(System.in);
int[] count = new int[10];
int i = count.length-1;
int position = -1;
int num = kb.nextInt();
while(i > 0)
{
if(count[i] == num)
{
position = i;
break;
}
i--;
}
}
}