This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 3 months ago.
This post was edited and submitted for review 3 months ago and failed to reopen the post:
Original close reason(s) were not resolved
I'm not new at Java, but I'm in JUnit. I'm having a problem with a simple for loop. I'm ordering array elements with bubble sorting, but I don't know why the two last elements disappear during the loop. I know it will be a little tiny thing, but I can't find the mistake. Could you help me, please?
This is my class:
package exercise5;
public class Ejercicio5 {
public static int[] sort(int[] arrayNums) {
// array that I have tried: {6,5,8,3,7,1}; [6]
System.out.println("size: " + arrayNums.length);
for (int j = 0; j < arrayNums.length; j++) {
System.out.println("j:" + j);
if (arrayNums[j] > arrayNums[j + 1]) {
System.out.println("entra");
int numGuardado = arrayNums[j + 1];
arrayNums[j + 1] = arrayNums[j];
arrayNums[j] = numGuardado;
}
print(arrayNums);
}
return arrayNums;
}
public static void print(int[] arrayParaImprimir) {
System.out.println("Array:");
for (int j = 0; j < arrayParaImprimir.length; j++) {
if (j != arrayParaImprimir.length - 1) {
System.out.print(arrayParaImprimir[j] + ", ");
} else {
System.out.print(arrayParaImprimir[j] + "\n");
}
}
}
}
My TestClass with JUnit5:
package exercise5;
import org.junit.Assert;
import org.junit.jupiter.api.Test;
import junit.framework.TestCase;
public class Ejercicio5Test extends TestCase{
#Test
public void resultadoCorrecto(){
int[] correct = {1,3,5,6,7,8};
int[] array = {6,5,8,3,7,1};
int[] result = Ejercicio5.sort(array);
Assert.assertArrayEquals(result, correct);
}
#Test
public void resultadoIncorrecto(){
int[] correct = {1,3,5,6};
int[] array = {3,5,6,1};
int[] result = Ejercicio5.sort(array);
Assert.assertArrayEquals(result, correct);
}
}
When j is equal to 4, the ordering is doing: 5, 6, 3, 7, 1, 8
but when j passed to 5, two elements disappear.
In addition, in my Test class there are only two methods, but, when I run it, it recognises one more and give me an error:
This is the array that I have tried {1,3,5,6,7,8} and this is that I expected {5,6,3,7,1,8} with 6 of array's size, not element disappearing.
enter image description here
This is the output in console. NOT ArrayIndexOutOfBounds. Only disappear 2 elements, and the size changes, not throwing any exceptions:
size: 6
j:0
entra
Array:
5, 6, 8, 3, 7, 1
j:1
Array:
5, 6, 8, 3, 7, 1
j:2
entra
Array:
5, 6, 3, 8, 7, 1
j:3
entra
Array:
5, 6, 3, 7, 8, 1
j:4
entra
Array:
5, 6, 3, 7, 1, 8
j:5
size: 4
j:0
Array:
3, 5, 6, 1
j:1
Array:
3, 5, 6, 1
j:2
entra
Array:
3, 5, 1, 6
j:3
for (int j = 0; j < arrayNums.length; j++) {
This loops for every number in the input. Then you..
if (arrayNums[j] > arrayNums[j + 1]) {
Compare this to the next number in the input. On the last loop, you are therefore comparing the last number (arrayNums[j]) with the.. number after that. Which doesn't exist, hence, ArrayIndexOutOfBoundsEx.
You want to loop one fewer.
You missed one loop here is the correct code -
public class Ejercicio5 {
//you don't need to return as it modifies exiting array
public static void sort(int arr[])
{
int n = arr.length;
for (int i = 0; i < n - 1; i++)
for (int j = 0; j < n - i - 1; j++)
if (arr[j] > arr[j + 1]) {
// swap arr[j+1] and arr[j]
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
/* Prints the array */
public static void printArray(int arr[])
{
int n = arr.length;
for (int i = 0; i < n; ++i)
System.out.print(arr[i] + " ");
System.out.println();
}
public static void main(String args[])
{
int[] array = {6,5,8,3,7,1};
Ejercicio5.sort(array);
System.out.println("Sorted array");
Ejercicio5.printArray(array);
}
}
output - Sorted array 1 3 5 6 7 8
and your testcases should work now with minor changes
If you run the JUnit test, it runs all the methods annotated by #Test.
Your output exactly reflects the 2 calls of your sort function, first from resultadoCorrecto() to line "j:5", second call from resultadoIncorrecto(), what outputs lines after that (from "size: 4").
So nothing has disappeared.
resultadoCorrecto() calls sort function with an array size of 6.
resultadoIncorrecto() calls sort function with an array size of 4.
Your bubble sort problem:
The for loop must go until index < length-1.
You must bubbling up all the bubbles with another for cycle around. (See Sagar Kale's answer.)
Related
I am working on an HW assignment that asks to write a method called count that determines the number of times a target value appears in an array. For example, if your array is [2, 3, 3, 3, 4, 6, 7, 8, 8, 9], the value 8 appears twice and the number 4 appears once. You should know that the method has two parameters and one return value. The code works but the problem that I am having is when I print the statement "The value x[i] appears count(x,x[i]) times" it repeats the same statement when it should only print the statement for each value. I need help on making it so it will only print the statement as long as the value is different from the one before it if it is the same as the value before it the code should skip and move on to the next value in the array until it prints everything.
import java.util.Arrays;
public class Q7 {
public static void main(String[] args) {
int[] x = { 2, 3, 3, 3, 4, 6, 7, 8, 8, 9 };
System.out.println(Arrays.toString(x));
for (int i = 0; i < x.length; i++) {
System.out.println("The value " + x[i] + " appears " + count(x, x[i]) + " times.");
}
}
public static int count(int[] array, int target) {
int counter = 0;
for (int i = 0; i < array.length; i++) {
if (array[i] == target) {
counter++;
}
}
return counter;
}
}
Output:
[2, 3, 3, 3, 4, 6, 7, 8, 8, 9]
The value 2 appears 1 times.
The value 3 appears 3 times.
The value 3 appears 3 times.
The value 3 appears 3 times.
The value 4 appears 1 times.
The value 6 appears 1 times.
The value 7 appears 1 times.
The value 8 appears 2 times.
The value 8 appears 2 times.
The value 9 appears 1 times.
in the case of your example (because the array is sorted), you can just
change
for (int i = 0; i < x.length; i++)
to
for (int i = 0; i < x.length; i = i + count(x, x[i]))
It will skip duplicate items.
You must somehow remember for which values you have already printed the message. there are several ways to do this. For example, you could sort your array and only output the message if you hit a value you didn't have yet while iterating. Another simple approach would be to add the elements to a set to get unique values of the array. Example with a set:
public static void main(String[] args) {
int[] x = { 2, 3, 3, 3, 4, 6, 7, 8, 8, 9 };
System.out.println(Arrays.toString(x));
Set<Integer> set = new HashSet<>();
for (int i = 0; i < x.length; i++) {
if(set.add(x[i])){
System.out.println("The value " + x[i] + " appears " + count(x, x[i]) + " times.");
}
}
}
I need to write a program which defines two arrays of int's and prints all elements of the first array which do not appear in the second, but each value once only, without repetitions (the order of printed values is irrelevant).
For example for arrays:
int[] arr = { 4, 3, 4, 3, 6, 7, 4, 8, 2, 9 };
int[] brr = { 2, 3, 6, 8, 1, 5 };
The result should be:
7 4 9
It only use the java.lang. package and it can't create any arrays, collections or Strings.
This prints all elements of the first array which do not appear in the second, now you just have to check for repetitions.
public static void compareArrays(int[] arr1, int[] arr2) {
boolean equal = false;
int[] printed = null;
for (int i = 0; i < arr1.length; i++) {
for (int x = 0; x < arr2.length; x++) {
if (arr1[i] == arr2[x]) {
equal = true;
break;
} else {
equal = false;
}
}
if (equal != true) {
System.out.println(arr1[i]);
}
}
}
public static void main(String[] args) {
int[] arr = { 4, 3, 4, 3, 6, 7, 4, 8, 2, 9 };
int[] brr = { 2, 3, 6, 8, 1, 5 };
compareArrays(arr, brr);
}
I will give you some pointers, but will not provide any code as I've not seen any attempt from your side. You can tackle this problem several ways, have a look and try to implement this yourself. You will learn much more during the process, rather than if someone gives you a complete full-code answer. So here goes:
First method:
Create a new ArrayList that will hold your output.
Iterate through the first array, iterate through the second array. Compare each value.
If value is not present and is not present in the output list (you would need to check for that specifically, so you dont have repetition of values), then add it to output list.
Print output list.
Second method:
Convert both arrays into an ArrayList.
Use the removeAll() method provided with Lists to get difference between the arrays. This will be stored in one of the lists you created earlier.
Remove repetitive items from the list (e.g. using Streams).
Third method:
Create a new ArrayList that will hold your output.
Iterate through values of array1.
Initialize a boolean variable (e.g. call it contains) that will determine whether a value from array1 is present in array2 using an IntStream.
Create if statement - if contains is true, add the value to your output list. Check that your output List already doesn't have the value and only add if it doesn't. Print output list.
Try using this instead:
String[] unique = new HashSet<String>(Arrays.asList(arr)).toArray(new String[0]);
for (int uEach : unique) {
for (int bEach : brr) {
if (unique[uEach] == brr[bEach]) {
ArrayUtils.removeElement(unique, uEach);
}
}
};
System.out.print(unique);
You can use to get distanct value from an array:
int[] unique = Arrays.stream(arr).distinct().toArray();
Then loop over both arrays and match strings if not found print that:
int i, j, occ;
int[] arr = { 4, 3, 4, 3, 6, 7, 4, 8, 2, 9 };
int[] brr = { 2, 3, 6, 8, 1, 5 };
arr = Arrays.stream(arr).distinct().toArray();
for (i = 0; i < arr.length; i++) {
occ = 0;
for (j = 0; j < brr.length; j++) {
if (arr[i] == brr[j]) {
occ++;
}
}
if (occ == 0) {
System.out.println(arr[i]);
}
}
static void findMissing(int a[], int b[]) {
for (int i = 0; i < a.length; i++) {
int j;
for (j = 0; j < b.length; j++) {
if (a[i] == b[j]) {
break;
}
}
if (j == b.length) {
System.out.print(a[i] + " ");
}
}
}
Hi, I'm a newbie to Java and I was doing this lab assignment where we compare elements of two arrays to get the common elements. I am stuck on how to get rid of duplicates.
My current code is giving me the output [3, 0, 5, 6, 5, 0, 9, 0] and the desired output of common is [3, 5, 6, 9, 0, 0, 0, 0].
Also, since I am not that experienced, please do not post professional ways to do the problem or "experienced" answers to my question, as that would not help me at all :D.
Thanks!
public static void main (String[] args) {
int[] a1 = {3, 8, 5, 6, 5, 8, 9, 2};
int[] a2 = {5, 15, 4, 6, 7, 3, 9, 11, 9, 3, 12, 13, 14, 9, 5, 3, 13};
int[] common = new int[a1.length];
System.out.println("Exercise 3: ");
findCommon(a1,a2,common);
}
public static void findCommon(int[] a1, int[]a2, int[] common) {
int num = 0;
for (int i = 0; i < common.length; i++)
{
for (int j = 0; j < a2.length; j++)
{
if (a1[i] == a2[j]) // loops through every index of j, while keeping i at one index
num = a1[i];
for (int k = 0; k < common.length; k++) // makes sure there are no duplicates in common
{
if (num != common[k])
common[i] = num;
}
}
}
for (int elements : common)
System.out.print(elements + " ");
}
You should look into using Sets to do this kind of thing, but since this is an exercise I've provided a solution with some comments along the way in the code.
Basically you should break the problem down into pieces, each of which is its own method. That way you will have an easier time getting it straight.
arrayIntersect(int[], int[])
This method's job is to create an array from two arrays. The resulting array must have unique elements that are present in both arrays.
You can do n. 1 with a helper method (mentioned below).
inArray(int, int[])
This method returns true if an array contains the given element, false otherwise.
Example
public static void main (String[] args) {
int[] a1 = {3, 8, 5, 6, 5, 8, 9, 2};
int[] a2 = {5, 15, 4, 6, 7, 3, 9, 11, 9, 3, 12, 13, 14, 9, 5, 3, 13};
int[] a3 = arrayIntersect(a1, a2);
for (int a : a3) {
System.out.println(a);
}
}
private static int[] arrayIntersect(int[] a1, int[] a2) {
int[] intersect = new int[Math.min(a1.length, a2.length)];
int curIndex = 0;
for (int x : a1) {
if (inArray(x, a2) && !inArray(x, intersect)) {
intersect[curIndex] = x;
curIndex++;
}
}
// resize intersect array to not include unused indexes
int[] tmp = intersect;
intersect = new int[curIndex];
for (int i = 0; i < intersect.length; i++) {
intersect[i] = tmp[i];
}
return intersect;
}
private static boolean inArray(int element, int[] array) {
boolean result = false;
for (int a : array) {
if (element == a) {
result = true;
break;
}
}
return result;
}
You are very close to the correct anwser, but the for loop for (int k = 0; k < common.length; k++) is being executed for every element of a2. So, when an value exist for a1 but doesn't exist for a2, you are putting the old value of num at the common array. If you look at the elements printed, you will see that every time that an element just exist in a1, the element repeat.
The result of the code is
3 3 5 6 5 5 9 9
You put the right identation, but forgot the curly brackets. If you put the curly brackets at the if (a1[i] == a2[j]), this will be the result:
3 0 5 6 5 0 9 0
But why these 0 are there? Because when you create an int array in java, all elements start with the value of 0. And you are putting the common elements at the same position of the presence of this elements in the a1 array. You can correct this by populating the int array with an invalid number and them ignorin it. At this code, I assumed that -1 is an invalid value.
public static void findCommon(int[] a1, int[] a2, int[] common) {
int num = 0;
for (int i = 0; i < common.length; i++) {
common[i] = -1;
}
for (int i = 0; i < common.length; i++) {
for (int j = 0; j < a2.length; j++) {
if (a1[i] == a2[j]) { // loops through every index of j, while keeping i at one index
num = a1[i];
for (int k = 0; k < common.length; k++) // makes sure there are
// no duplicates in common
{
if (num != common[k])
common[i] = num;
}
}
}
}
for (int elements : common) {
if (elements != -1)
System.out.print(elements + " ");
}
}
If you see, At the if (elements != -1) I didn't put the curly brackets but it worked. If you don't put the curly brackets, it will just execute the next command.
I'm looking for a hint on how to solve this or where I am going wrong.
The question is as follows: Write a static method named stretch that accepts an array of integers as a parameter and returns a new array twice as large as the original, replacing every integer from the original array with a pair of integers, each half the original. If a number in the original array is odd, then the first number in the new pair should be one higher than the second so that the sum equals the original number. For example, if a variable named list refers to an array storing the values {18, 7, 4, 24, 11}, the call of stretch(list) should return a new array containing {9, 9, 4, 3, 2, 2, 12, 12, 6, 5}. (The number 18 is stretched into the pair 9, 9, the number 7 is stretched into 4, 3, the number 4 is stretched into 2, 2, the number 24 is stretched into 12, 12 and the number 11 is stretched into 6, 5.)
Test your code with the following class:
import java.util.*;
public class TestStretch {
public static void main(String[] args) {
int[] list = {18, 7, 4, 14, 11};
int[] list2 = stretch(list);
System.out.println(Arrays.toString(list)); // [18, 7, 4, 24, 11]
System.out.println(Arrays.toString(list2)); // [9, 9, 4, 3, 2, 2, 7, 7, 6, 5]
}
// your code goes here
}
This is currently what I have, but it is not quite working correctly... I have a feeling it is how i'm using int i and int j, but i'm not sure what to do to fix it so that it works as intended.
import java.util.*;
public class TestStretch {
public static void main(String[] args) {
int[] list = {18, 7, 4, 14, 11};
int[] list2 = stretch(list);
System.out.println(Arrays.toString(list)); // [18, 7, 4, 24, 11]
System.out.println(Arrays.toString(list2)); // [9, 9, 4, 3, 2, 2, 7, 7, 6, 5]
}
public static int[] stretch(int[] array){
int length = array.length;
int[] newArray = new int[array.length*2];
for(int i = 0; i< length; i=i+2){
int j = 0;
if(array[i] % 2 == 0){
newArray[i] = (array[j]/2);
newArray[i+1] = newArray[i];
j++;
} else{
newArray[i] = (array[j]/2);
newArray[i+1] = (newArray[i] + 1);
j++;
}
}
return newArray;
}
}
The output I get is:
[18, 7, 4, 14, 11]
[9, 9, 9, 9, 9, 10, 0, 0, 0, 0]
Instead of:
[18, 7, 4, 24, 11]
[9, 9, 4, 3, 2, 2, 7, 7, 6, 5]
There are a couple of mistakes:
The loop iterates only until half of the array, skipping elements by 2
The value of j is reset to 0 in each iteration
Also, the algorithm can be simplified:
For each index i in the input, you want to set in the destination at position 2 * i and 2 * i + 1.
The second value to set is simply the original value divided by 2, with integer truncation
The first value to set is the same as the second, +1 if the division by 2 leaves a remainder
With the above issues corrected, and the implementation simplified:
int[] newArray = new int[array.length * 2];
for (int i = 0; i < array.length; i++) {
newArray[2 * i] = array[i] / 2 + array[i] % 2;
newArray[2 * i + 1] = array[i] / 2;
}
return newArray;
First of all, if you are looping to the old array's length, don't increment i by 2.
If i increases by 1 each time, we need to figure out how to map the old array's index i to the new array's index. It is quite simple: the new array's indices are just i*2 and i*2+1.
Now j seems redundant because it always holds the same value as i, so you can remove that.
This is the full code:
int length = array.length;
int[] newArray = new int[array.length*2];
for(int i = 0; i< length; i++){
if(array[i] % 2 == 0){
newArray[i*2] = (array[i]/2);
newArray[i*2+1] = newArray[i*2];
} else{
newArray[i*2] = (array[i]/2);
newArray[i*2+1] = (newArray[i*2] + 1);
}
}
return newArray;
Three mistakes:
j should be initialized outside the for-loop
we should use j to record the new value into the new array
we should increment j upon every iteration in 2 - and we should increment i only by 1 (since we're using j to insert two item while we use i to iterate the original array):
int j = 0;
for(int i = 0; i< length; i++){
if(array[i] % 2 == 0){
newArray[j] = newArray[j+1] = array[i]/2;
} else{
newArray[j] = array[i]/2 + 1;
newArray[j+1] = array[i]/2;
}
j += 2;
}
Note: giving a variable that holds an array the name "list" might create confusion!
for(int i = 0; i< length; i=i+2){
length is the length of the original array, so you iterate only over half of the values because you increase i by 2 each step.
if(array[i] % 2 == 0){
This should be
if(array[j] % 2 == 0){
And because you define j within your for-loop, array[j] always returns 18. Oh and you set the second element of the tuple to be the higher one while your comment in the code says the contrary should take place.
So a fixed version of your method would look like this:
public static int[] stretch(int[] array){
int length = array.length;
int[] newArray = new int[array.length*2];
int j = 0;
for(int i = 0; i< newArray.length; i=i+2){
if(array[j] % 2 == 0){
newArray[i] = (array[j]/2);
newArray[i+1] = newArray[i];
} else{
newArray[i+1] = (array[j]/2);
newArray[i] = (newArray[i+1] + 1);
}
j++;
}
return newArray;
}
Avoiding duplicate code:
public static int[] stretch(int[] array){
int[] newArray = new int[array.length*2];
int j = 0;
for(int i = 0; i< newArray.length; i=i+2){
int val = array[j];
newArray[i] = (val/2);
newArray[i+1] = newArray[i];
if(val % 2 != 0){
newArray[i]++;
}
j++;
}
return newArray;
}
Or using fancy streams:
public static int[] stretch(int[] array){
return Arrays.stream(array)
.flatMap(elem -> {
int half = elem / 2;
int otherHalf = half;
if (elem % 2 != 0) {
half++;
}
return IntStream.of(half, otherHalf);
}).toArray();
}
}
I am a newbie to programming. I am trying to create a program that would display an array in reverse. Plus also find the even and odd numbers of an array,sum the count and also display the even and odd numbers. The code works but the problem is that it also reverses the even and odd arrays and it shows this weird zero in those arrays. What am I doing wrong?
Please also provide explanation. Thanks!
import java.util.Arrays;
public class ArrayTest {
public static void main(String[] args)
{
int[] array = {1,2,3,4,5,6,7,8,9,10,11,12,13};
for ( int i=0; i<array.length/2; i++ )
{
int temp = array[i];
array[i] = array[array.length-(1+i)];
array[array.length-(1+i)] = temp;
}
System.out.println("Array after reverse: \n" + Arrays.toString(array));
int even=0;
int odd=0;
int[] Even = new int[13];
int[] Odd = new int[13];
for ( int i=0; i<array.length; i++)
{
if (array[i] % 2 == 0)
{
Even[i] = array[i];
even++;
}
else
{
Odd[i] = array[i];
odd++;
}
}
System.out.println("Even: "+even+" ");
System.out.println(Arrays.toString(Even));
System.out.println("Odd: "+odd+" ");
System.out.println(Arrays.toString(Odd));
}
}
The output is:
Array after reverse:
[13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
Even: 6
[0, 12, 0, 10, 0, 8, 0, 6, 0, 4, 0, 2, 0]
Odd: 7
[13, 0, 11, 0, 9, 0, 7, 0, 5, 0, 3, 0, 1]
You need to correct your logic
int[] Even = new int[(array.length/2)+1];
int[] Odd = new int[(array.length/2)+1];
for ( int i=0; i<array.length; i++)
{
if (array[i] % 2 == 0)
{
Even[even] = array[i];
even++;
}
else
{
Odd[odd] = array[i];
odd++;
}
}
As per you code, you are initializing array of size 13 for odd and even, which is not correct.
int[] Even = new int[13];
int[] Odd = new int[13];
So, by default, Even and Odd array will be initialized by 0 value. Then, you are setting value as per main array, which a size of 13 on alternate basis (even/odd).
==Updated==
Since, you don't want Even and Odd array in reverse order. Then, you can move the code up.
>>Demo<<
You faced 2 problems (I guess so)
The odd and even arrays are also in reverse order
Reason: The first For loop reverses the 'array' and stores the results in array itself. So, the next time when you try working with 'array' to find odd/even numbers, you are actually working with the reversed array.
Solution: You can assign the original array to a backup array and use that backup array to find odd and even nos.
Unnecessary zeros:
Reason: In your second for loop you used odd[i]=array[i] which seems to be a logical error in your code. Consider the case:
value of i : 0 1 2 3 4 5 ... 12
value of array[i]: 1 2 3 4 5 6 ... 13
value of odd[i] : 1 0 3 0 5 0 ... 13
value of even[i] : 0 2 0 4 0 6 ... 0
This means, the control inside for loop is made to flow either to if{} block or the else{} block and not the both. So, when if(condition) is satisfied, then even[i] array will be updated. But meanwhile what happens to the odd[i] array? It retains the inital value '0'. That's it!
I hope the following code helps you:
import java.util.Arrays;
public class A
{
public static void main(String[] args)
{
int[] array = {1,2,3,4,5,6,7,8,9,10,11,12,13};
int[] arr2 = new int[array.length]; // backup array
arr2=Arrays.copyOfRange(array,0,array.length);
for ( int i=0; i<arr2.length/2; i++ )
{
int temp = arr2[i];
arr2[i] = arr2[arr2.length-(1+i)];
arr2[arr2.length-(1+i)] = temp;
}
System.out.println("Array after reverse: \n" + Arrays.toString(arr2));
int even=0;
int odd=0;
int[] Even = new int[13];
int[] Odd = new int[13];
for ( int i=0; i<array.length; i++)
{
if (array[i] % 2 == 0)
{
Even[even] = array[i];
even++;
}
else
{
Odd[odd] = array[i];
odd++;
}
}
Even=Arrays.copyOfRange(Even,0,even);
Odd=Arrays.copyOfRange(Odd,0,odd);
System.out.println("Even: "+even+" ");
System.out.println(Arrays.toString(Even));
System.out.println("Odd: "+odd+" ");
System.out.println(Arrays.toString(Odd));
}
}
Note: I have used Arrays.copyOfRange(array,start,end) function to copy a certain part of the array from start to end-1 position.
Output:
Array after reverse:
[13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
Even: 6
[2, 4, 6, 8, 10, 12]
Odd: 7
[1, 3, 5, 7, 9, 11, 13]
Hope this helps :)
--Mathan Madhav
You select even and odd numbers from reversed array.
You use wrong index for even and odd arrays.
If you don't want to see zeros in output, use print in for statement. Another solution - firstly count odd and even numbers and create arrays with exact size.
import java.util.Arrays;
public class ArrayTest {
public static void main(String[] args)
{
int[] array = {1,2,3,4,5,6,7,8,9,10,11,12,13};
int even=0;
int odd=0;
int[] Even = new int[13];
int[] Odd = new int[13];
for ( int i=0; i<array.length; i++)
{
if (array[i] % 2 == 0)
{
Even[even++] = array[i];
}
else
{
Odd[odd++] = array[i];
}
}
for ( int i=0; i<array.length/2; i++ )
{
int temp = array[i];
array[i] = array[array.length-(1+i)];
array[array.length-(1+i)] = temp;
}
System.out.println("Array after reverse: \n" + Arrays.toString(array));
System.out.println("Even: "+even+" ");
System.out.println(Arrays.toString(Even));
System.out.println("Odd: "+odd+" ");
System.out.println(Arrays.toString(Odd));
}
}