这段代码是输入n
integer
个值并计算出个数。这些输入值中的偶数
和奇数
值。
此java代码在使用do..while
循环时显示ArrayIndexOutOfBoundsException
,但是当使用for
循环时它工作正常。没有改变任何东西,只是重新排列了语法,以便将 for
循环转换为 do while
循环。
FOR 循环:
import java.util.*;
public class EvenOddCount
{
public static void main(String args[]) throws Exception
{
System.out.print("Enter the no. of inputs to be taken : ");
int evenCount=0, oddCount=0;
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int a[] = new int[n];
System.out.println("Enter the inputs : ");
for(int i=0;i<n;i++)
a[i] = sc.nextInt();
for(int i=0;i<a.length;i++)
{
if(a[i]%2==0)
evenCount++;
else
oddCount++;
}
System.out.println("\nThe number of even numbers in input numbers are : "+evenCount);
System.out.println("The number of odd numbers in input numbers are : "+oddCount);
}
}
上面的代码运行良好并给出了合适的输出。
DO...WHILE 循环:
import java.util.*;
public class EvenOddCount
{
public static void main(String args[]) throws Exception
{
System.out.print("Enter the no. of inputs to be taken : ");
int evenCount=0, oddCount=0, i=0;
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int a[] = new int[n];
System.out.println("Enter the inputs : ");
do
{
a[i] = sc.nextInt();
i++;
} while (i<n);
do
{
if(a[i]%2==0)
evenCount++;
else
oddCount++;
i++;
} while (i<a.length);
System.out.println("\nThe number of even numbers in input numbers are : "+evenCount);
System.out.println("The number of odd numbers in input numbers are : "+oddCount);
}
}
上面的代码有一个运行时异常,即
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
at EvenOddCount.main(EvenOddCount.java:20)
最佳答案
在原始代码中,您有两个单独的 i
变量:
for(int i=0;i<n;i++)
...
for(int i=0;i<a.length;i++)
在您的 do/while
版本中,您有一个 i
变量。一旦完成第一个循环,i
的值将是 n
- 但您开始第二个循环而不将其重置为 0,因此在第一个循环中迭代它将超出范围。
您可以通过添加来解决这个问题:
i = 0;
就在第二个 do
/while
循环之前,但请注意,您仍然会遇到问题(即使在第一个循环中) ) 如果 n
为 0,因为您直到迭代结束才检查条件。如果您使用:
while (i < n)
和
while (i < a.length)
相反,它将在第一次迭代之前检查条件,因此当n
为0时它将执行0次。(您仍然需要在之前将i
重置为0不过第二个循环。)
关于java - 如何解决Java中的线程错误(ArrayIndexOutOfBoundsException)异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52468771/