import java.util.Scanner; //importing scanner to get user input
public class ArrayHelper
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int[] hello = new int[10];
for(int i = 0; i < 10; i++) //to get right number of integers
{
System.out.print("Please enter an integer: ");
hello[i] = input.nextInt();
}
//printing everything out
display(hello);
System.out.println();
System.out.print("Evens: ");
display(onlyEvens(hello));
System.out.println();
System.out.print("Positives: ");
display(onlyPositives(hello));
System.out.println();
System.out.print("Odds: ");
display(disjoint(hello ,onlyEvens(hello)));
System.out.println();
System.out.print("Negatives: ");
display(disjoint(hello ,onlyPositives(hello)));
System.out.println();
}
public static void display(int[] nums)
{
for(int i = 0; i < nums.length -1; i++)
System.out.print(nums[i] + ", ");
System.out.print(nums[nums.length - 1]); //!!!!!!this is where the error occurs
}
public static int[] onlyEvens(int[] nums) //only even numbers in array (anything divisible by 2 including 0)
{
int x = 0; //for set length
for(int i = 0; i < nums.length; i++)
if (nums[i]%2 == 0) //checks if even
x++;
int[] y = new int[x];
int z = 0;
for(int i = 0; i < nums.length; i++)
if (nums[i]%2 == 0) //checks if even
{
y[z] = nums[i];
z++;
}
return y;
}
public static int[] onlyPositives(int[] nums) //looking for only positive integers in array
{
int x = 0; //sets set length
for(int i = 0; i < nums.length; i++)
if (nums[i] > -1) //checks if positive
x++;
int[] y = new int[x];
int z = 0;
for(int i = 0; i < nums.length; i++)
if (nums[i] > -1) //checks if positive
{
y[z] = nums[i];
z++;
}
return y;
}
public static int[] disjoint(int[] nums, int[] nums2)
{
int x = 0;
for(int i = 0; i < nums.length; i++)
{
int j = nums[i];
if(!contains(nums2 , j)) //checks if letter be there
x++;
}
for(int i = 0; i < nums2.length; i++)
{
int j = nums2[i]; //checks if letter be there
if(!contains(nums , j))
x++;
}
int[] y = new int[x];
int z = 0;
for(int i = 0; i < nums.length; i++)
{
int j = nums[i]; //checks if letter be there
if(!contains(nums2 , j))
{
y[z] = nums[i];
z++;
}
}
for(int i = 0; i < nums2.length; i++)
{
int j = nums2[i]; //checks if letter be there
if(!contains(nums , j))
{
y[z] = nums2[i];
z++;
}
}
return y;
}
}
this is a program that takes in user input to get 10 integers to create an array. I have all of the program done, and there are no compile time errors, but when I run the code, there's an index out of bounds (-1) problem in the display method and ive done everything to try and fix it. thank you!