Home > OS >  Problem numbering in array sorting even and odd JAVA for looops
Problem numbering in array sorting even and odd JAVA for looops

Time:11-06

I am having a trouble in this numbering when it is arranged in even and odd My problem is that the 'Arranged Elements'in output number were jumbled.

Source Code:

import java.util.*;
public class Main {
   public static void main(String[] args)
   {
     Scanner x = new Scanner (System.in);
     System.out.print("Enter the number of elements: ");
     int elements = x.nextInt();

     int a[]= new int[elements];
     for(int y=0;y<a.length;y  )
     {
        System.out.print("Element #" (y 1) ": ");
        a[y]=x.nextInt();
     }

     System.out.println("");
     System.out.println("Arranged Elements:");

     for(int y=0;y<a.length;y  )
     {
        if(a[y]%2==0)
        {
           System.out.println("Element #" (y) ": " a[y]);
        }

     }

     for(int y=0;y<a.length;y  )
     {
         if(a[y]%2!=0)
         {
            System.out.println("Element #" (y) ": " a[y]);
         }
     }
     
   }      
}

Output:

Enter the number of elements: 4

Element #1: 6
Element #2: 5
Element #3: 17
Element #4: 12

Arranged Elements:
Element #0: 6
Element #3: 12
Element #1: 5
Element #2: 17

Possilbe Output:

Enter the number of elements: 4
Element #1: 6
Element #2: 5
Element #3: 17
Element #4: 12

Arranged Elements:
Element #1: 6
Element #2: 12
Element #3: 5
Element #4: 17

Can someone help me out and solve this problem? Thank you!

CodePudding user response:

You need an external int that holds the index, also for nicer code you can use for-each loops

int idx = 0;
for (int val : a) {
    if (val % 2 == 0) {
        System.out.println("Element #"   (  idx)   ": "   val);
    }
}
for (int val : a) {
    if (val % 2 != 0) {
        System.out.println("Element #"   (  idx)   ": "   val);
    }
}

CodePudding user response:

If you want to fix the element numbering in your code, you just add an extra variable to keep track of it, see elementNumber variable in the code below and how it is used.

System.out.println("");
System.out.println("Arranged Elements:");

// Store the number of the elements printed so far is this variable
int elementNumber=0;
for(int y=0;y<a.length;y  )
{
  if(a[y]%2==0)
  {
    elementNumber  
    System.out.println("Element #" (elementNumber) ": " a[y]);
  }
}


for(int y=0;y<a.length;y  )
{
  if(a[y]%2!=0) 
  {
    elementNumber  
    System.out.println("Element #" (elementNumber) ": " a[y]);
  }
}   
  •  Tags:  
  • java
  • Related