Week 1 - Friday
What did we talk about last time? Java: Types if statements
But there's sometimes a cleaner way to express a list of possibilities Enter: the switch statement
switch( data ) { case value1: statements 1; case value2: statements 2; … case valuen: statements n; default: default statements; }
switch( base ) { case 'A': System.out.println("Adenine"); break; case 'C': System.out.println("Cytosine"); break; case 'G': System.out.println("Guanine"); break; case 'T': System.out.println("Thymine"); break; default: System.out.println("Your base" + "doesn't belong to us"); break; // unnecessary }
Both "Three" int data = 3; and "Four" switch( data ) { are printed case 3: System.out.println("Three"); case 4: System.out.println("Four"); break; case 5: System.out.println("Five"); The } break is The default optional is optional too
1. The data that you are performing your switch on must be an int , a char , or a String 2. The value for each case must be a literal 3. Execution will jump to the case that matches 4. If no case matches, it will go to default 5. If there is no default , it will skip the whole switch block 6. Execution will continue until it hits a break
switch( base ) { case 'A': case 'a': System.out.println("Adenine"); break; case 'C': case 'c': System.out.println("Cytosine"); break; case 'G': case 'g': System.out.println("Guanine"); break; case 'T': case 't': System.out.println("Thymine"); break; default: System.out.println("Your base doesn't belong to us"); break; // unnecessary }
Using if -statements is usually safer if -statements are generally clearer and more flexible switch statements are only for long lists of specific cases Be careful about inconsistent use of break
1. while loops Used when you don’t know how many times you are going to need to repeat 2. for loops Used when you do know how many times you are going to repeat 3. do-while loops Used never Oh, okay, they are used whenever you need to be guaranteed the loop runs at least once
Any problem that uses loops can use any kind of loop The choice is supposed to make things easier on the programmer Some loops are more convenient for certain kinds of problems
The simplest loop in Java is the while loop It looks similar to an if statement The difference is that, when you get to the end of the while loop, it jumps back to the top If the condition in the while loop is still true , it executes the body of the loop again
while( condition ) { statement1; A whole statement2; bunch of … statements statementn; }
A while loop will usually have multiple statements in its body However, it is possible to make a while loop with only a single statement while( condition ) statement; Then, like an if -statement, the braces are optional
Let's print the numbers from 1 to 100 We could do this with lots of cut/paste, or: int i = 1; while( i <= 100 ) { System.out.println(i); i++; }
The while loop executes each statement one by one When execution gets to the bottom, it jumps to the top If the condition is still true (i.e., i <= 100 ), it repeats the loop
for loops are great when you know how many times a loop will run They are the most commonly used of all loops They are perfect for any task that needs to run, say, 100 times A for loop has 3 parts in its header: Initialization 1. 2. Condition Increment 3.
Starting Point Way to Progress for( init; condition; inc ) { statement1; statement2; … Ending statementn; Point }
A for loop will usually have multiple statements in its body However, it is possible to make a for loop with only a single statement for( init; condition; inc ) statement; Then, like if -statements and while -loops, the braces are optional
Let's print the numbers from 1 to 100 (again) Remember how this was done with while : int i = 1; while( i <= 100 ) { System.out.println(i); i++; }
A for loop is specifically designed for this sort of thing: for( int i = 1; i <= 100; i++ ) { System.out.println(i); } The initialization and the increment are built-in
They work just like while loops The only difference is that they are guaranteed to execute at least once Unlike a while loop, the condition isn’t checked the first time you go into the loop Sometimes this is especially useful for getting input from the user The syntax is a little bit different
do { statement1; statement2; … statementn; } while( condition );
Loops are great But, without a way to talk about a list of variables, we can’t get the full potential out of a loop Enter: the array
An array is a homogeneous , static data structure Homogeneous means that everything in the array is the same type: int , double , String , etc. Static (in this case) means that the size of the array is fixed when you create it
To declare an array of a specified type with a given name : type[] name; Example with a list of type int : int[] list; Just like any variable declaration, but with []
When you declare an array, you are only creating a variable that can hold an array At first, it holds nothing, also know as null To use it, you have to create an array, supplying a specific size: int[] list; list = new int[100]; This code creates an array of 100 int s
You can access an element of an array by indexing into it, using square brackets and a number list[9] = 142; System.out.println(list[9]); Once you have indexed into an array, that variable behaves exactly like any other variable of that type You can read values from it and store values into it Indexing starts at 0 and stops at 1 less than the length
When you instantiate an array, you specify the length Sometimes (like in the case of args ) you are given an array of unknown length You can use its length member to find out int[] list = new int[42]; int size = list.length; System.out.println("List has " + size + " elements"); //prints 42
When you create an int , double , char , or boolean array, the array is automatically filled with certain values Type Value int 0 double 0.0 char '\0' boolean false For other types, including String s, each index in the array must be filled explicitly
Explicit initialization can be done with a list: String[] days = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"}; Or, a loop could be used to set all the values: String[] numbers = new String[100]; for(int i = 0; i < numbers.length; i++) numbers[i] = "" + (i + 1);
An array takes up the size of each element times the length of the array Each array starts at some point in computer memory The index used for the array is actually an offset from that starting point That’s why the first element is at index 0
We can imagine that we have an array of type int of length 10 Java decides what address in memory is going to be used, but let’s say it starts at 524 Addresses 524 528 532 536 540 544 548 552 556 560 12 43 -9 6 789 0 -23 23 10 6 0 1 2 3 4 5 6 7 8 9 Indexes
Arrays are a fixed size list of a single kind of data A for loop is ideal for iterating over every item and performing some operation for loops and arrays will crop up again and again Of course, a while loop can be used with an array, but it rarely is
Imagine that we have an array of int s called list Let's use a for loop to sum up those int s int sum = 0; for( int i = 0; i < list.length; i++ ) sum += list[i]; We don’t even need to know how big the array is ahead of time
So far, our code has been inside of the main() method What about a big program? The main() method is going to get really long and hard to read Sometimes you need to do similar things several times: Read some input and check that it falls within certain values Draw a green hexagon at several different locations Find the square root of several different numbers
Methods allow you to package up some code to run over and over Methods usually take some input (like numbers or Strings ) so that they can be customized Methods often give back an answer (like the square root of a number) Also called functions in some other languages
More modular programming Break a program into separate tasks Each task could be assigned to a different programmer Code reusability Use code over and over Even from other programs (like Math.sqrt() ) Less code duplication Improved readability Each method can do a few, clear tasks
Recommend
More recommend