20
Iteration and Simple Menus Deterministic / Non- deterministic loops and simple menus

Iteration and Simple Menus Deterministic / Non-deterministic loops and simple menus

Embed Size (px)

Citation preview

Page 1: Iteration and Simple Menus Deterministic / Non-deterministic loops and simple menus

Iteration and Simple Menus

Deterministic / Non-deterministic loops and

simple menus

Page 2: 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

Page 3: Iteration and Simple Menus Deterministic / Non-deterministic loops and simple menus

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");}

Page 4: Iteration and Simple Menus Deterministic / Non-deterministic loops and simple menus

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

Page 5: Iteration and Simple Menus Deterministic / Non-deterministic loops and simple menus

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}

Page 6: Iteration and Simple Menus Deterministic / Non-deterministic loops and simple menus

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?

Page 7: Iteration and Simple Menus Deterministic / Non-deterministic loops and simple menus

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…

Page 8: Iteration and Simple Menus Deterministic / Non-deterministic loops and simple menus

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];

Page 9: Iteration and Simple Menus Deterministic / Non-deterministic loops and simple menus

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!

Page 10: Iteration and Simple Menus Deterministic / Non-deterministic loops and simple menus

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--;}

Page 11: Iteration and Simple Menus Deterministic / Non-deterministic loops and simple menus

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!

Page 12: Iteration and Simple Menus Deterministic / Non-deterministic loops and simple menus

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.

Page 13: Iteration and Simple Menus Deterministic / Non-deterministic loops and simple menus

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:

Page 14: Iteration and Simple Menus Deterministic / Non-deterministic loops and simple menus

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

Page 15: Iteration and Simple Menus Deterministic / Non-deterministic loops and simple menus

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

?

Page 16: Iteration and Simple Menus Deterministic / Non-deterministic loops and simple menus

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;}

Page 17: Iteration and Simple Menus Deterministic / Non-deterministic loops and simple menus

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();

}

Page 18: Iteration and Simple Menus Deterministic / Non-deterministic loops and simple menus

Implementing amenu-based interface

Would have to write appropriate methods showMenu() registerStudent() changeProgram()

Look at StudentInterface.java listing

Page 19: Iteration and Simple Menus Deterministic / Non-deterministic loops and simple menus

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).

Page 20: Iteration and Simple Menus Deterministic / Non-deterministic loops and simple menus

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.