Upload
ashlyn-holmes
View
212
Download
0
Embed Size (px)
Citation preview
Iteration and Simple Menus
Deterministic / Non-deterministic loops and
simple menus
Where are we?
The 6 Coding Concepts
Input – getting things into the program Output – passing things to the outside world Assignment – pass a value from one part of
the program to another Sequence - do each thing in the order specified Decision-making -check something then do
the appropriate action depending on that condition
Repetition - do the set of commands several times
Deterministic loops (for loop)
Use if you know how many times the loop should execute (deterministic loop)
int num = Console.readInt("How many lines?");for (int i = 0; i < num; i++){ System.out.println("I must stay awake in
class");}
Breakdown of the for Loop
for (int i = 0; i < num; i++)
What does this mean? The for loop consists of 3 items:
The initialiser (int i = 0) The terminating condition (i < num) The incrementor (i++)
These items are separated by a semicolon ; Like the if statement, you can omit the {}
that follow it if there is only one statement to be repeated
Nested for loops You have seen how if-else statements can be
nested inside each other:
if(condition ){ if(condition )
{ // do something}else{ // do something different}
}else{ // other stuff}
Nested for loops
Well you can do the same with for loops:
for( int i = 0; i < 10; i++ ){ System.out.println(“Outer loop”);
for( int j = 0; j < 5; j++ ){ System.out.println(“Inner loop”);}
}
Why use i and j as loop counters?
Loop examples
for( int i = 0; i < 10; i++ ) – will repeat 10 times by incrementing i
for( int i = 0; i <= 10; i++ ) – will repeat 11 times
for( int i = 0; i < 10; i+=2 ) – will repeat 5 times
for( int i = 10; i > 0; i-- ) – will repeat 10 times by decrementing i
for(;;) – will repeat infinitely! Hint: there may be a way out…
Alternative syntax: For-Each There is another way of specifying the Java for
loop when using arrays and collections.
int [] myArray;// or you could write int myArray[];
for(int nValue : myArray) // foreach in other languages
sum += nValue;
instead of:for(int i=0; i < myArray.length; i++)
sum += myArray[i];
A short digression – reading ints
If we need to read an integer value from the keyboard, we might do this:
import java.util.*;
private int getConsoleInt(String sPrompt)
{ System.out.print(sPrompt);
Scanner scan = new Scanner(System.in);
try{ return scan.nextInt(); }
catch (InputMismatchException ex) { return Integer.MIN_VALUE; }
catch (NoSuchElementException ex){ return Integer.MIN_VALUE; }
catch (IllegalStateException ex){ return Integer.MIN_VALUE; }
} // note that a return of –2,147,483,648 means an error occurred!
Non-deterministic loops (while)
use if you want the loop to execute until a condition is false (non-deterministic loop)
must allow tested variable to change within the loop, otherwise you’ll have an infinite loop!
int num = getConsoleInt ("How many lines?");
while (num > 0){ System.out.println("I love Java!!!");
num--;}
Non-deterministic loops (do-while) There is a similar while loop called the do-
while loop:
int num = getConsoleInt ("How many lines?");
do{ System.out.println("I love Java!!!");
num--;}while (num > 0);
Note the semi-colon!
Non-deterministic loops (do-while) So what’s the difference between while
and do-while? The contents of a while loop is not
executed if the test condition fails at the start.
The contents of a do-while loop is guaranteed to execute at least once.
The test condition is only performed after the first iteration through the loop.
Exiting a loop
The normal way to exit a loop is for the condition that is tested to become false.
This is true of all three types of loops in Java: for, while, and do-while.
However, there might be times when you want a loop to end immediately, even if the condition being tested is still true.
You can do this with a break statement, as shown in the following code:
The break statement
int index = 0;
while (index <= 1000){ index = index + 5; // or index+=5;
if (index == 400) break;System.out.println("The index is " + index);
}
The break statement is especially handy if you need to search a list and then exit the search loop code if you found what you are looking for
Menus
Can use a combination of a while loop and a switch statement to implement a menu
NB may be better to have “[0] Exit” - why?
What would you like to do?[1] Register student[2] Register student on program[3] Exit
?
Simple menu display
public int showMenu(){ int choice;
System.out.println("\nWhat would you like to do?");System.out.println("\t[1]\tRegister student");System.out.println("\t[2]\tChange student's program");System.out.println("\t[3]\tExit");
choice = getConsoleInt ("? ");
return choice;}
Simple menu controlint choice = showMenu();while (choice != 3){ switch (choice)
{ case 1: registerStudent(); break;
case 2: changeProgram(); break;
default: System.out.print(“Invalid, please try
again");}choice = showMenu();
}
Implementing amenu-based interface
Would have to write appropriate methods showMenu() registerStudent() changeProgram()
Look at StudentInterface.java listing
Summary
We have looked at: for loops Nested for loops while loops do-while loops break
We have put them together into a menu-driven interface for the Student class (see tutorial).
Further work
Practical Read http://www.faqs.org/docs/javap/c3/s1.html
to go over all the main blocks of Java code you’ve seen so far.