Saturday, April 30, 2016

Even / Odd Array Index

In some cases, you might have to process array values where only every other value needs to be processed.  This example should help you understand the process including how to use Regular Expressions.  


public class GradeSplit{
      public static void main(String[] args){
            String input="claude 99 mike 89 paul 88";
            //Review regular expression syntax
            //https://docs.oracle.com/javase/7/docs/api/
            // \\s will split on white space and the + is matching the white 

            //        space character one or more times
            //Look at the Java API's String class split method, you'll see that it returns a String[]
            //Thus every even index will hold names ( generate even index numbers by 2*i )
            //and every odd index will hold the grade value ( generate odd index values by 2*i+1 )

            String[] data=input.split("\\s+");
            
//Since you always have pairs of values, divide the length by 2 
             //to generate an array holding only the grades
            int[] x=new int[data.length/2];                       //add break point and examine data array

            //fill the array to hold grades by parsing all odd index values
            for(int i=0;i<x.length;i++){
                   x[i]=Integer.parseInt(data[2*i+1]);      
//add break point and step through the loop
             }

 
          //print all even values from the original array and all values 
            //from the grade array - processed as parallel array
            for(int i=0;i<x.length;i++){
                  System.out.printf("Your name is: %-6s and your grade is: %3d\n", data[2*i],x[i]);
            }
      }
}


Thus you can calculate the index value to use in your code by simple arithmetic calculations. Computer Science is about problem solving by pattern recognition where pattern recognition does not work without writing things down on paper in a logical fashion until a pattern emerge.

index odd values even values
index*2+1 index*2
0 1 0
1 3 2
2 5 4
3 7 6
4 9 8
5 11 10
6 13 12


Contents of data array after the split operation.




Contents of x integer array that is half of the data array and now only containing values as integers.

 



Output of code above
Your name is: claude and your grade is:  99
Your name is: mike    and your grade is:  89
Your name is: paul     and your grade is:  88


No comments:

Post a Comment