Lecture 3
Loops and Data Structures
Loops
Definition
A loop is a way of repeating lines of code more than once. The block of code contained within the loop will be executed again and again until the condition required by the loop is met. In Java There are 3 loops statements
For Loop While Loop
Do..While Loop
Types of Loops
Determinate (For Loop)
a determinate loop knows exactly how many times it will loop.
For Example:
If you want to print the word java 12 times
Indeterminate( While loop and Do...While Loop )
an indeterminate loop does not know how many times it will run. For Example you could search through an int array looking for a specific value. The most logical way would be to search each element of the array in order until you find the right value. You don't know if the value is in the first element or the last .
For Loop Syntax
Start with index at 0
Condition While this condition is true the loop continues
Every time the loop continues the index is incremented by 1
For Loop Example Public static void main(String[] args) { for (int i =0; i< 12 ; i++) { System.out.println(Java); } }
Infinite Loop Public static void main(String[] args) { for ( ; ; ) { System.out.println(Java); }
}
While Loop Syntax
The Condition While this condition is true the loop will contains
While Loop Example
Public static void main(String [] args) {
int[] numbers = {1, 23, 56, 89, 3, 6, 9, 10, 123}; boolean numberFound = false; // a boolean variable that will act as the condition for the loop int index = 0; //this loop will continue running until numberFound = true while (!numberFound)
{
System.out.println("We're looping around.."); if (numbers[index] == 10) { numberFound = true; System.out.println("We've found the number " );` } index++;
Do..While Loop Syntax
Same as while loops except it will be executed at least one time.
Do..While Example
Public static void main(String [] args) { int x = -1 ; do { System.out.println(x); } while(x>0); }
Excercises
1.
Make an application that takes an input string and reverse it Make an application that calculates how many number an input string repeated.
Sample input I can say hello to say yes
2.
Search for : say Output : repeated 2 times
Data Structures
Why to use Data structures
What
if you want to store the daily temperature values for the whole year. Will you make a 356 variable to store them ?!
if you want to store student marks and you dont know how many subject he has ? , You will ask him at first then ?
What
Data Structures in Java
Fixed Size 1. Array Dynamic Size (collections) 1. ArrayList 2. TreeSet , HashSet 3. TreeMap , HashMap
Array
is a data structure that stores fixed number of data elements of the same type. Array elements are indexed in a zero-based fashion. ( first element index is zero).
Declaration
datatype [] arrayName ; Example : int x [] ; datatype arrayName [] ; Example : int [] x ;
Initialization
Datatype [] arrayName = new datatype [size];
Array elements type
For Example int[] numbers = new int[5];
Identifier
Array elements type
Array Size
double nums = new double [10]; String words = new String[3];
Initialization
Datatype [] arrayName = {element1 , element2 ,};
Array elements type
For Example :
Identifier
Array Elements
int [] numbers ={ 10 , 50 , 40 , 20 , 7 }; String [] names ={ adel, ali , m7md };
Array Example double mylist = new double[10];
Length
Arrays have an instance variable length, which gives the capacity of the array.
int x [] = new int [10]; x.length; Note that length is an instance variable associated with arrays, while length() is a method associated with strings.
Week Temperature Average Example
double[] temperatureValues; // declares the array
temperatureValues = new double[7]; //create it
temperatureValues[0] = 30; // initialize first element temperatureValues[1] = 31; // second element temperatureValues[2] = 32.5; // etc. temperatureValues[3] = 30; temperatureValues[4] = 29; temperatureValues[5] = 18; temperatureValues[6] = 18;
Arrays with loops
Usually loops is the way you fill and retrieve array elements.
for(int i=0 ; i < array.length ; i++)
{
// code to enter the value array[i] = insertedValue; }
Exercises
1.
Student grades average program
Search for a number inside an array Find maximum number in array Add fees to salaries Program
2.
3.
4.
Collections
Collections
A collection is an object that can be used for storing, retrieving and manipulating groups of items. To use Collections we must import java.util.*
They use the wrapper class of any datatype
For more about collections visit this link
http://www.tutorialspoint.com/java/java_collections.htm
Wrapper Classes
1) ArrayList
Objects of the generic class ArrayList are similar to arrays, but have differences:
Similarities
Both can store a number of references the data can be accessed via an index.
Differences
An ArrayList can automatically increase in capacity as necessary
The ArrayList object requests more space from the Java run-time system, if necessary.
The ArrayList is not ideal in its use of memory.
As soon as an ArrayList requires more space than its current capacity, the system will allocate more memory space for it. The extension is more than required for the items about to be added. So there will often be empty locations within an ArrayList that is, the size will often be less than the capacity.
Two important terms in connection with ArrayList objects:
The capacity of an ArrayList object is the maximum number of items it can currently hold (without being extended). The size of an ArrayList object is the current number of items stored in the ArrayList.
Declaration
How to declare an ArrayList?
Ex1: ArrayList<String> list1 = new ArrayList<String>(); This declaration of an ArrayList specifies that it will hold String references The type String can be replaced by any object type.
This declaration sets up an empty ArrayList The initial capacity is set to a default value. The ArrayList capacity is expanded automatically as needed when items are added.
Ex2:
ArrayList<Date> list2 = new ArrayList<Date>(100);
This declaration of an ArrayList specifies that it will hold Date references The type Date can be replaced by any object type. This declaration can be used to specify the initial capacity in this case 100 elements. This can be more efficient in avoiding repeated work by the system in extending the list, if you know approximately the required initial capacity.
For more about Arraylists visit http://www.tutorialspoint.com/java/java_arraylist_class.htm
Arraylist Example
Conversion
ArrayList To Array
List<String> myArrayList = new ArrayList<String>(); String[] myArray = myArrayList.toArray(newString[myArrayList.size()]);
Array
To ArrayList
new ArrayList(Arrays.asList(myArray));
Set
The same as the ArrayList in every thing same concept and same methods Difference
1. 2.
There is no duplication It has two types HashSet (unordered list)
TreeSet (ordered list)
For more about sets visit http://www.tutorialspoint.com/java/java_hashset_class.htm http://www.tutorialspoint.com/java/java_treeset_class.htm
TreeSet Example
Set<Integer> numbers = new TreeSet<Integer>();
numbers.add(5);
numbers.add(2);
System.out.println(numbers); // "[2, 5] System.out.println(numbers.contains(7)); // "false System.out.println(numbers.add(5)); // "false" System.out.println(numbers.size()); // "2"
HashSet Example
Set<Integer> numbers = new HashSet<Integer>();
numbers.add(5);
numbers.add(2);
System.out.println(numbers); // "[5, 2]
System.out.println(numbers.contains(7)); // "false
System.out.println(numbers.add(5)); // "false"
System.out.println(numbers.size()); // "2"
Printing or getting the elements inside ArrayList or a Set
Using for each for accessing each element on the list
Example : List<String> list= new ArrayList<String>() ; for(String item : list) { System.out.println(item); }
For more about accessing elements in a list http://www.mkyong.com/java/how-to-loop-arraylist-in-java/
Maps
In many applications we require two types of object to be associated with each other
Example: user-name and password (see figure)
A hash table can store pairs of linked items in keyvalue pairs. In Java, the programmer must specify the type of both the key and the value; for example, <String, Integer>
Declaration and Initialization
Two types of maps
Hashmap (unordered map) Treemap (ordered map by keys)
How to declare a HashMap? Similar to ArrayList but with the types of both the key and value.
HashMap<String,String> table1 = new HashMap<String,String>();
HashMap<String,String> table2 = new HashMap<String,String>(10);
For more about Hashmaps and Treemaps http://www.tutorialspoint.com/java/java_hashmap_class.htm
http://www.tutorialspoint.com/java/java_treemap_class.htm
Map Methods
Map Example
Examples
1. Calculating
2. Address
the average using Set
book example
Questions ?
END