此代码用于输入n
integer
值并计算no。这些输入值中的even
和odd
值。
这段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)
发布于 2018-09-24 02:04:39
您需要重置i的值:
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);
https://stackoverflow.com/questions/52468771
复制相似问题