首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在Java中解决线程错误中的异常(ArrayIndexOutOfBoundsException)?

如何在Java中解决线程错误中的异常(ArrayIndexOutOfBoundsException)?
EN

Stack Overflow用户
提问于 2018-09-24 01:51:31
回答 1查看 2.4K关注 0票数 0

此代码用于输入n integer值并计算no。这些输入值中的evenodd值。

这段java代码在使用do..while循环时显示了ArrayIndexOutOfBoundsException,但是当使用for循环时,它工作得很好。我没有改变任何东西,只是重新排列了语法,以便将for循环转换为do while循环。

FOR循环:

代码语言:javascript
复制
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循环:

代码语言:javascript
复制
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);
}
} 

上面的代码有一个运行时异常,即

代码语言:javascript
复制
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
at EvenOddCount.main(EvenOddCount.java:20)
EN

回答 1

Stack Overflow用户

发布于 2018-09-24 02:04:39

您需要重置i的值:

代码语言:javascript
复制
do
{
    a[i] = sc.nextInt();
    i++;
} while (i<n);
i =0;
do
{
    if(a[i]%2==0)
        evenCount++;
    else 
        oddCount++;
    i++;
} while (i<a.length);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52468771

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档