So, the method is supposed to go into the array, choose the positive numbers, and then store those even numbers in a different array.
I have tried debugging checks, tried switching values in the if statement, but nothing has worked. I am still new to dealing with arrays, so I apologize if this has a really simple solution that I am missing.
public static void main(String[] args)
{
int [] arr = {2, 1, 4, 3, 6, 5, 8, 7};
int[] arr3 = {1, 2, 1, 2, 3, 4, 5, 1, 2, 3};
int[] arrEvens;
arrEvens = removeEvens(arr);
System.out.println("\nNew array of even values: ");
for (int i : arrEvens)
System.out.print(i " ");
System.out.println();
arrEvens = removeEvens(arr3);
System.out.println("\nNew array of even values: ");
for (int i : arrEvens)
System.out.print(i " ");
System.out.println();
```
public static int[] removeEvens(int[] arr)
{
int[] newArr = arr;
int count = 0;
for(int i = 0; i < arr.length; i )
{
if (arr[i] % 2 == 0)
{
newArr[count] = arr[i];
count ;
}
}
return newArr;
}
It should only print out 2468 for arr and 2242 for arr3, but it actually prints 24686587 and 2242345123 respectively
CodePudding user response:
First, to create newArr
in the method removeEvens
, you need to know how many even numbers in arr
. But for this you need to traverse the array and count even numbers.
public static int[] removeEvens(int[] arr)
{
int[] newArr;
int count = 0;
for (int j : arr) {
if (j % 2 == 0) {
count ;
}
}
newArr = new int[count];
count = 0;
for (int i: arr){
if (i % 2 == 0){
newArr[count ] = i;
}
}
return newArr;
}
In this solution you will traverse array two times.
There is also another solution:
public static int[] removeEvens(int[] arr)
{
int[] newArr = new int[arr.length];
int count = 0;
for (int j : arr) {
if (j % 2 == 0) {
newArr[count ] = j;
}
}
if (count < arr.length) newArr[count] = -1;
return newArr;
}
First, you will create newArr
's length as arr
's length. Insert even numbers into newArr
and mark with -1 end of even numbers. In main method, to print returned array do this:
public static void main(String[] args) {
int[] arr = {2, 1, 4, 3, 6, 5, 8, 7};
int[] arr3 = {1, 2, 1, 2, 3, 4, 5, 1, 2, 3};
int[] arrEvens;
arrEvens = removeEvens(arr);
System.out.println("\nNew array of even values: ");
for (int i : arrEvens) {
if (i == -1) break;
System.out.print(i " ");
}
System.out.println();
arrEvens = removeEvens(arr3);
System.out.println("\nNew array of even values: ");
for (int i : arrEvens) {
if (i == -1) break;
System.out.print(i " ");
}
}
CodePudding user response:
Cause of your output related memory allocations. Read about heap and stack memory parts. You thought that you created newArr
, but got the previous array itself. newArr
and arr
are just name of array. They are stored in stack memory. But values of this arrays are stored in heap memory and both of these arrays bound to one array which is stored in heap.
If you need new array, you need create with new int[n]
.