1 estruturas de controle márcia j. n. rodrigues lucena marciaj@dimap.ufrn.br especialização em...

Post on 17-Apr-2015

104 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

1

Estruturas de Controle

Márcia J. N. Rodrigues Lucenamarciaj@dimap.ufrn.br

Especialização em Técnicas e Ferramentas de Apoio à DecisãoDepartamento de Informática e Matemática Aplicada

Universidade Federal do Rio Grande do Norte

Transparências baseadas no capítulo 5 do livro Deitel e Deitel

2

Estruturas de Controle - Parte 2

Roteiro5.1 Introdução5.2 Repetição controlada por contador5.3 Estrutura de Repetição FOR5.4 Exemplos5.5 Estrutura de Seleção Múltipla switch5.6 Estrutura de repetição do/while5.7 Instruções break e continue5.8 Instruções rotuladas break e continue5.9 Operadores Lógicos5.10 Resumo

3

5.1 Introdução

Antes de escrever um programa Ter um entendimento do problema Planejamento cuidadoso para resolvê-lo

Ao escrever um programa Conhecer quais tipos de blocos de construção

existem Utilizar bons princípios de programação

4

Bloco

Qualquer número de instruções simples que são delimitadas por um par de chaves ({})

Os blocos definem o escopo das variáveis.public static void main(String[] args) {

int n;

// ...

{ int k; // k é local, pertence ao bloco e

/* ... */ } // definida somente até o final

} // do bloco

5

5.2 Repetição Controlada por contador

Repetição controlada por contador requer Nome de uma variável de controle (ou contador de laço) Valor inicial Condição que testa o valor final da variável de controle

(ou seja se o laço deve continuar) Incremento pelo qual a variável de controle é

modificada a cada passagem do laço Exemplo a seguir de um applet

6

1// Fig. 5.1: WhileCounter.java

2// Counter-controlled repetition

3import java.awt.Graphics;

4import javax.swing.JApplet;

5

6public class WhileCounter extends JApplet {

7 public void paint( Graphics g )

8 {

9 int counter = 1; // initialization10

11 while ( counter <= 10 ) { // repetition condition12 g.drawLine( 10, 10, 250, counter * 10 );

13 ++counter; // increment

14 }

15 }

16}

7

Algoritmo

1. import

2. Class WhileCounter

3. Método Paint

3.1 Inicialização do contador

3.2 Loop

3.3 chamada do método drawline

3.4 Incremento

Program Output

8

5.2 Repetição Controlada por contador

Variável de controle é nomeada e iniciada Declarações com inicialização são instruções executáveis

Condição para testar o valor da variável

Método drawLine( x1, y1, x2, y2 ) Referencia o objeto Graphics Desenha linha de (x1, y1) para (x2, y2)

Incrementa o contador

9 int counter = 1; // initialization

11 while ( counter <= 10 ) { // repetition condition

12 g.drawLine( 10, 10, 250, counter * 10 );

13 ++counter; // increment

9

5.2 Repetição Controlada por contador

Este programa pode ser mais conciso Inicializando o contador com zero

while ( ++counter <= 10 ) g.drawLine( 10, 10, 250, counter * 10 );

O incremento é feito dentro do while

10

5.3 Estrutura de Repetição For

Vamos refazer o exemplo anterior usando a estrutura For

11

Loop using for

Program Output

1// Fig. 5.2: ForCounter.java

2// Counter-controlled repetition with the for structure

3import java.awt.Graphics;

4import javax.swing.JApplet;

5

6public class ForCounter extends JApplet {

7 public void paint( Graphics g )

8 {

9 // Initialization, repetition condition and incrementing10 // are all included in the for structure header.

11 for ( int counter = 1; counter <= 10; counter++ )

12 g.drawLine( 10, 10, 250, counter * 10 );

13 }

14}

12

5.3 Estrutura de Repetição For

No for temos :inicializãção, condição e incremento Formato geralfor (inicialização; teste de continuação do loop; incremento )

instrução Se existem muitas instruções utilize as chaves para delimitar o

bloco Variável controle existe apenas no corpo da estrutura for Se o teste de condição é inicialmente false o corpo do for não é

nem executado

11 for ( int counter = 1; counter <= 10; counter++ )

12 g.drawLine( 10, 10, 250, counter * 10 );

13

5.3 Estrutura de Repetição For

Pode ser usada expressão aritmética Seja x = 2, y = 10for ( int j = x; j <= 4 * x * y; j += y / x )

Equivalente afor ( int j = 2; j <= 80; j += 5 )

For pode ser representada por uma estrutura whileinicialização;while ( condição teste) {

instrução incremento;

}

14

5.3 Estrutura de Repetição For11 for ( int counter = 1; counter <= 10; counter++ )

12 g.drawLine( 10, 10, 250, counter * 10 );

verd

falso

int counter = 1

counter <= 10 counter++

g.drawLine( 10, 10, 250, counter * 10 );

Inicializa o valor da variável de controle

Determina se o valor final da variável de controle foi alcançado Corpo do laço pode

conter muitas instruções

Incrementa a varia'vel de controle

15

5.4 Exemplos

Calcular o valor de um depósito de R$1000 com taxa de juros de 5% ao ano

Calcular para 10 anos Use a = p (1 + r )n

p – quantidade original r – taxa de juros anual n – número de anos a – quantidade em depósito no fim do n-ésimo ano

Use um laço for para calcular o valor

n

16

Use for loop to calculate interest

1// Fig. 5.6: Interest.java2// Calculating compound interest3import java.text.DecimalFormat;4import javax.swing.JOptionPane;5import javax.swing.JTextArea;67public class Interest {8 public static void main( String args[] )9 {10 double amount, principal = 1000.0, rate = .05;1112 DecimalFormat precisionTwo = new DecimalFormat( "0.00" );13 JTextArea outputTextArea = new JTextArea( 11, 20 );1415 outputTextArea.append( "Year\tAmount on deposit\n" );1617 for ( int year = 1; year <= 10; year++ ) {18 amount = principal * Math.pow( 1.0 + rate, year );19 outputTextArea.append( year + "\t" +20 precisionTwo.format( amount ) + "\n" );21 }2223 JOptionPane.showMessageDialog(24 null, outputTextArea, "Compound Interest",25 JOptionPane.INFORMATION_MESSAGE );2627 System.exit( 0 ); // terminate the application28 }29}

17

Saída do programa

18

5.4 Exemplos

variáveis

Classe DecimalFormat (package java.text) String de controle de formato indica a apresentação dos números ponto

flutuante "0.00" Dois dígitos a direita do decimal e pelo menos 1 a esquerda Método format retorna um String formatado

Classe JTextArea (package javax.swing) Componente gráfico que mostra muitas linhas Inicializado para apresentar 11 linhas e 20 colunas de texto

10 double amount, principal = 1000.0, rate = .05;

12 DecimalFormat precisionTwo = new DecimalFormat( "0.00" );

13 JTextArea outputTextArea = new JTextArea( 11, 20 );

19

5.4 Exemplos

Método append (of class JTextArea) Adiciona texto no objeto JTextArea Inicialmente possui string vazio

Laço for executa 10 vezes Método pow (class Math)

Math.pow( x, y ) Retorna um double

15 outputTextArea.append( "Year\tAmount on deposit\n" );

21 }

17 for ( int year = 1; year <= 10; year++ ) {18 amount = principal * Math.pow( 1.0 + rate, year );19 outputTextArea.append( year + "\t" +20 precisionTwo.format( amount ) + "\n" );

20

5.4 Exemplos

static método showMessageDialog Classe JOptionPaneshowMessageDialog mostra um String ou

componente GUI, como JTextArea

23 JOptionPane.showMessageDialog(

24 null, outputTextArea, "Compound Interest",

25 JOptionPane.INFORMATION_MESSAGE );

21

1// Fig. 5.6: Interest.java

2// Calculating compound interest

33import java.text.DecimalFormat;

4import javax.swing.JOptionPane;

5import javax.swing.JTextArea;

6

7public class Interest {

8 public static void main( String args[] )

9 {

10 double amount, principal = 1000.0, rate = .05;

11

12 DecimalFormat precisionTwo = new DecimalFormat( "0.00" );

1313 JTextArea outputTextArea = new JTextArea( 11, 20 );

14

15 outputTextArea.append( "Year\tAmount on deposit\n" );

16

17 for ( int year = 1; year <= 10; year++ ) {

1818 amount = principal * Math.pow( 1.0 + rate, year );

1919 outputTextArea.append( year + "\t" +

2020 precisionTwo.format( amount ) + "\n" );

21 }

22

2323 JOptionPane.showMessageDialog(

24 null, outputTextArea, "Compound Interest",

25 JOptionPane.INFORMATION_MESSAGE );

26

27 System.exit( 0 ); // terminate the application

28 }

29}

Notice the import statements required.

New JTextArea object initialized to hold 11 rows and 20 columns of text.

new operator used to create new objects.

Use method append to add to the String in the JTextArea object.

Notice the format of method Math.pow

Use method format to output the formatted number as a String.

Use the JTextArea reference as an argument to showMessageDialog

22

1. import

2. Class Interest

2.1 Initialize variables

2.2 DecimalFormat

3. for loop

3.1 Math.pow

3.2 append

3.3 format

3.4 showMessageDialog

Algoritmo

23

Saída do Programa

24

5.5 Estrutura Switch

switch Estrutura de múltipla seleção

Format Série de rótulos case e um opcional default caseswitch ( value ){

case value1:actions

case value2:actions

default:actions

} break; sai da estrutura

25

5.5 Estrutura Switch

true

false

.

.

.

case a case a action(s) break

case b case b action(s) break

false

false

case z case z action(s) break

true

true

default action(s)

26

5.5 Estrutura Switch

Method init Entrada do usuário

9 public void init()

10 {11 String input;1213 input = JOptionPane.showInputDialog( 14 "Enter 1 to draw lines\n" +

15 "Enter 2 to draw rectangles\n" +16 "Enter 3 to draw ovals\n" );

1718 choice = Integer.parseInt( input );19 }

7 int choice;

27

5.5 Estrutura Switch

Estrutura switch - compara choice com cases case rótulos – pode ser valores do tipo byte, short, int, long e char Usa aspas simples para caracter: 'A' Pode haver múltiplas ações para cada case

break – sai da estrutura switch

Rótulo default – opcional, ação pode ser tomada caso não ocorra nenhum dos rótulos acima

24 switch( choice ) {

25 case 1:

26 g.drawLine( 10, 10, 250, 10 + i * 10 );

27 break;

36 default:

37 JOptionPane.showMessageDialog(

38 null, "Invalid value entered" );

28

1. Class SwitchTest

2. init

3. paint

3.1 for

3.2 switch

1// Fig. 5.7: SwitchTest.java2// Counting letter grades3import java.awt.Graphics;4import javax.swing.*;56public class SwitchTest extends JApplet {7 int choice; 89 public void init()10 {11 String input;1213 input = JOptionPane.showInputDialog( 14 "Enter 1 to draw lines\n" +15 "Enter 2 to draw rectangles\n" +16 "Enter 3 to draw ovals\n" );1718 choice = Integer.parseInt( input );19 }2021 public void paint( Graphics g )22 {23 for ( int i = 0; i < 10; i++ ) { 2424 switch( choice ) {2525 case 1:26 g.drawLine( 10, 10, 250, 10 + i * 10 );2727 break;28 case 2:29 g.drawRect( 10 + i * 10, 10 + i * 10,30 50 + i * 10, 50 + i * 10 );31 break;

Notice how case labels are used to test for the integer entered.

break exits the switch structure.

Place the value to compare inside the switch statement.

29

Program Output

34 50 + i * 10, 50 + i * 10 );

35 break;

3636 default:

37 JOptionPane.showMessageDialog(

38 null, "Invalid value entered" );

39 } // end switch

40 } // end for

41 } // end paint()

42} // end class SwitchTest

32 case 3:33 g.drawOval( 10 + i * 10, 10 + i * 10,

30

31

5.6 Estrutura do while

Similar a estrutura while Condição é testada depois do corpo do laço Açoes são executadas pelo menos uma vez

Formato do {

instrução }

while ( condição );

Boa prática coloca chaves mesmo se não for requerido

32

5.6 Estrutura do while

true

false

action(s)

condition

33

1// Fig. 5.9: DoWhileTest.java

2// Using the do/while repetition structure

3import java.awt.Graphics;

4import javax.swing.JApplet;

5

6public class DoWhileTest extends JApplet {

7 public void paint( Graphics g )

8 {

9 int counter = 1;

10

1111 do {

1212 g.drawOval( 110 - counter * 10, 110 - counter * 10,

13 counter * 20, counter * 20 );

14 ++counter;

15 } while ( counter <= 10 );

16 }

17}Method drawOval( x1, y1, width, height )

Same arguments as drawRect, but the rectangle defines the oval's bounding box.

Notice format of do/while loop.

34

Algoritmo

1. Class DoWhileTest

2. paint

3. do/while loop

35

5.7 Instruções break e continue

break Saída imediata do while, for, do/while or switch

Continua a partir da próxima instrução depois do laço

Uso comum do breakSaída antecipada do laçoPula os outros rótulos da estrutura switch

36

5.7 Instruções break e continue

continue Pula as outras instruçoes do corpo do while, for ou do/while Procede com a próxima interação do laço

while e do/while A condição do laço é avaliada imediatamente após o continue

Estrutura for Expressão de incremento é executada, então o teste é avaliado

37

1// Fig. 5.11: BreakTest.java2// Using the break statement in a for structure3import javax.swing.JOptionPane;45public class BreakTest {6 public static void main( String args[] )7 {8 String output = "";9 int count;1011 for ( count = 1; count <= 10; count++ ) {12 if ( count == 5 )

1313 break; // break loop only if count == 51415 output += count + " ";16 }1718 output += "\nBroke out of loop at count = " + count;19 JOptionPane.showMessageDialog( null, output );20 System.exit( 0 );21 }22}

break causes an immediate exit from the loop.

38

1// Fig. 5.12: ContinueTest.java2// Using the continue statement in a for structure3import javax.swing.JOptionPane;45public class ContinueTest {6 public static void main( String args[] )7 {8 String output = "";910 for ( int count = 1; count <= 10; count++ ) {11 if ( count == 5 )

1212 continue; // skip remaining code in loop13 // only if count == 51415 output += count + " ";16 }1718 output += "\nUsed continue to skip printing 5";19 JOptionPane.showMessageDialog( null, output );20 System.exit( 0 );21 }

continue skips the rest of the body and goes to the next iteration.

39

1.

1// Fig. 5.13: BreakLabelTest.java

2// Using the break statement with a label

3import javax.swing.JOptionPane;

4

5public class BreakLabelTest {

6 public static void main( String args[] )

7 {

8 String output = "";

9

1010 stop: { // labeled compound statement

11 for ( int row = 1; row <= 10; row++ ) {

12 for ( int column = 1; column <= 5 ; column++ ) {

13

14 if ( row == 5 )

1515 break stop; // jump to end of stop block

16

17 output += "* ";

18 }

19

20 output += "\n";

21 }

22

23 // the following line is skipped

24 output += "\nLoops terminated normally";

25 }

26

Begins labeled compound statement stop:

Labeled break statement to exit stop block.

40

5.9 Operadores Lógicos

Operadores Lógicos Até o momento utilizamos <, >, ==, etc para testar

condições Operadores lógicos permitem condições mais

complexas && ( AND )

Retorna true se ambas condições são verdadeiras || ( OR )

Retorna true se pelo menos uma condição for verdaderia

41

5.9 Operadores Lógicos

! (NOT, negação) Inverte o significado de uma condição

Se a condição for false torna-se true Se a condição for true torna-se false

Operador unário, tem apenas um operando Como é feita a avaliação

Avalia o operando da esquerda, depois avalia o operando direita

Se o operando da esquerda de um && (and) for false, o operando da direita não será avaliado

42

5.9 Operadores Lógicos

Operadores Lógicos ^ (Ou exclusivo)

true se existe exatamente uma condição true AND Lógico (&) e Or inclusivo (|)

trabalha identico ao regular AND and ORSempre avalia as 2 expressõesUtil em situações como esta

birthday == true | ++age >= 65

43

5.9 Operadores Lógicos

ExemplosExpressão Resultado

true && false falsetrue || false true

!false truetrue ^ true false if ( ( gender == 1 ) && ( age >= 65 ) ) ++seniorFemales; seniorFemales é atualizado se ambas as condições são true

44

1. Class LogicalOperators

1.1 JTextArea

1.2 JScrollPane

2. Logical operators

1// Fig. 5.19: LogicalOperators.java

2// Demonstrating the logical operators

3import javax.swing.*;

4

5public class LogicalOperators {

6 public static void main( String args[] )

7 {

88 JTextArea outputArea = new JTextArea( 17, 20 );

99 JScrollPane scroller = new JScrollPane( outputArea );

10 String output = "";

11

12 output += "Logical AND (&&)" +

1313 "\nfalse && false: " + ( false && false ) +

14 "\nfalse && true: " + ( false && true ) +

15 "\ntrue && false: " + ( true && false ) +

16 "\ntrue && true: " + ( true && true );

17

18 output += "\n\nLogical OR (||)" +

19 "\nfalse || false: " + ( false || false ) +

20 "\nfalse || true: " + ( false || true ) +

21 "\ntrue || false: " + ( true || false ) +

22 "\ntrue || true: " + ( true || true );

23

24 output += "\n\nBoolean logical AND (&)" +

25 "\nfalse & false: " + ( false & false ) +

26 "\nfalse & true: " + ( false & true ) +

27 "\ntrue & false: " + ( true & false ) +

28 "\ntrue & true: " + ( true & true );

29

JTextArea can display many lines of text. This one can display 17 rows and 20 columns.

This creates a JScrollPane object and initializes it with outputArea. This adds scrolling to outputArea.

Use the logical operators. Boolean values converted to Strings.

45

3. setText

34 "\ntrue | true: " + ( true | true );

35

36 output += "\n\nBoolean logical exclusive OR (^)" +

37 "\nfalse ^ false: " + ( false ^ false ) +

38 "\nfalse ^ true: " + ( false ^ true ) +

39 "\ntrue ^ false: " + ( true ^ false ) +

40 "\ntrue ^ true: " + ( true ^ true );

41

42 output += "\n\nLogical NOT (!)" +

43 "\n!false: " + ( !false ) +

44 "\n!true: " + ( !true );

45

4646 outputArea.setText( output );

47 JOptionPane.showMessageDialog( null, scroller,

48 "Truth Tables", JOptionPane.INFORMATION_MESSAGE );

49 System.exit( 0 );

50 }

51 }

30 output += "\n\nBoolean logical inclusive OR (|)" +

31 "\nfalse | false: " + ( false | false ) +

32 "\nfalse | true: " + ( false | true ) +

33 "\ntrue | false: " + ( true | false ) +

Method setText replaces the String in the JTextArea.

46

47

5.10 Resumo Programação Estruturada

Programação estruturada Fácil de entender, testar, debug, modificar programas

Regras para programação estruturada1) inicie com um fluxograma simples

2) Qualquer retângulo (ação) pode ser substituído por 2 retângulos (ações) em sequência

3) Qualquer retângulo (ação) pode ser substituído por qualquer estrutura de controle (sequence, if, if/else, switch, while, do/while ou for)

4) Regras 2 e 3 são aplicadas quantas vezes necessárias e em qualquer ordem

 

48

5.10 Resumo Programação Estruturada

Rule 3

Rule 3Rule 3

Rule 3 - Troque qualquer retângulo por uma estrutura

49

5.10 Resumo Programação Estruturada

Todos os programas podem ser divididos em 3 partes Sequência - trivial Seleção - if, if/else, ou switch Repetição - while, do/while, or for

Programas são reducidos em Sequencia Estrutura if (seleção) Estrutura while (repetição) Estruturas de controle podem ser combinadas de 2 formas

Aninhamento (regra 3) e empilhamento (rule 2)

50

Switchint opcao =

javax.swing.JOptionPane.showInputDialog( "Digite um número entre 1 e 6");

switch (opcao) { case 1: System.out.println("um");

break; case 2: System.out.println("dois");

break; case 3: case 4: System.out.println("três ou quatro");

break; default: System.out.println("Valor inválido"); break;}

51

For

for (<inicialização>; <condição>; incrementador)for (int i = 0; i < 100; i++) { System.out.println(i);}

for (int i = 0, j = 10; i < j; i++, j--) { System.out.println(i);}

for (int i = 0; i < 100; ) { System.out.println(i); // Laço Infinito}

52

While

while (<condição>) <instrução>final int maximo = 50;int c = -10double f = 0;System.out.println("\tºC\t\tºF");while (f<maximo) { f = (9.0 / 5.0) * c + 32.0; System.out.println("\t" + c + "\t\t" + f); c++;}

ºC ºF

-10 14.0

-9 15.8

-8 17.6

-7 19.4

-6 21.2

-5 23.0

-4 24.8

-3 26.6

-2 28.4

-1 30.2

0 32.0

1 33.8

2 35.6

3 37.4

4 39.2

5 41.0

6 42.8

7 44.6

8 46.4

9 48.2

10 50.0

53

Do-While

do instruçãowhile (condição);int numero = 12345;int r = numero;int digitos = 0;do { r /= 10; digitos++;} while (r != 0);System.out.println(numero + " tem "+ digitos +

" digitos.");

54

For While

for (instrução1; condição; instrução2) instrução3;

instrução1;while (condição) { instrução3; instrução2;}

for (int i = 0; i < 100; i++) { System.out.println(i);}

int i = 0;

while (i < 100) {

System.out.println(i);

i++;

}

55

Do-While While

do instruçãowhile (condição)

instrução;while (condição) { instrução}

int i = 0;

do {

System.out.println(i);

i++;

} while (i < 100)

int i = 0;

System.out.println(i);

while (i < 100) {

System.out.println(i);

i++;

}

top related