I'm new to programming with java, so please be lenient with my silly errors. My problem is that my code isn't giving the output that I desire, which is to display all the even values of an array underneath each other and then all the uneven values of the array under each other. This is my code:
//main class
public class Even_number_array
{
public static void main(String[] args)
{
array_class obj = new array_class();
obj.set_numbers();
}
}
//another class
public class array_class
{
private int arr[] =
{
10, 20, 7, 8, 3, 6, 11, 9, 7, 45
};
public void set_numbers()
{
for (int i = 0; i <= arr.length; i++)
{
if (arr[i] % 2 == 0)
{
System.out.println("These even numbers were found in the array:");
do
{
System.out.println(arr[i]);
i++;
}
while (arr[i] % 2 == 0);
}
else if (arr[i] % 2 != 0)
{
System.out.println("uneven numbers found in array:");
do
{
System.out.println(arr[i]);
i++;
}
while (arr[i] % 2 != 0);
}
}
}
}
And this is my output (using Netbeans IDE which shows the errors I have, which I have included because I don't quite understand what it means.):
These even numbers were found in the array:
10
20
These even numbers were found in the array:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10
8
These even numbers were found in the array:
6
uneven numbers found in array:
9
7
45
at even_number_array.array_class.set_numbers(array_class.java:35)
at even_number_array.Even_number_array.main(Even_number_array.java:12)
Java Result: 1
I have a few questions, why is the number 8 in my array not printing with 10 and 20, and 6 printing separately like 8? And also, is there a way that I can get user input using the Scanner class for the array and how would I go about doing this?
Any help would be welcomed! Thanks in advance :)