Download presentation
Presentation is loading. Please wait.
1
Object Oriented Programming
Object Oriented Programming Lecture 06
2
For-each Loop www.hndit.com Purpose
The basic for loop was extended in Java 5 to make iteration over arrays and other collections more convenient. This newer for statement is called the enhanced for or for-each For-each loop Equivalent for loop for (type var :arr) { body-of-loop } for(int i=0; i <arr.length; i++) { type var = arr[i];
3
Example - Adding all elements of an array
Example - Adding all elements of an array Here is a loop written as both a for-each loop and a basic for loop. double[ ] ar = {1.2, 3.0, 0.8}; int sum = 0; for (double d : ar) { sum += d; }
4
for (int i = 0; i < ar.length; i++) { sum += ar[i]; }
And here is the same loop using the basic for. It requires an extra iteration variable. double[] ar = {1.2, 3.0, 0.8}; int sum = 0; for (int i = 0; i < ar.length; i++) { sum += ar[i]; }
5
int[ ] a={1,2,3,4,5,6,7,8,9,0}; for(int i : a){ System.out.println(i); }
6
Using Command-Line Arguments
Using Command-Line Arguments On many systems it is possible to pass arguments from the command line (these are known as command-line arguments) to an application by including a parameter of type String[] (i.e., an array of Strings) in the parameter list of main. When an application is executed using the java command, Java passes the command-line arguments that appear after the class name in the java command to the application's main method as Strings in the array args.
7
public class InitArray { public static void main( String args[] ) if ( args.length != 3 ) System.out.println( "Error: Please re-enter the entire command, including\n" + 12 "an array size, initial value and increment." ); else { int arrayLength = Integer.parseInt( args[ 0 ] ); int array[] = new int [ arrayLength ]; int initialValue = Integer.parseInt( args[ 1 ] ); int increment = Integer.parseInt( args[ 2 ] ) for ( int counter = 0; counter < array.length; counter++ ) array[ counter ] = initialValue + increment * counter; System.out.println( "Index" “\t Value" ); System.out.println( counter+”\t”+ array[ counter ] ); }
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.