1 / 27

Capitulo 6

Capitulo 6. Iterações. Ciclo while. while ( condição ) instruções ; Repete o ciclo enquanto a condição é verdadeira while (balance < 2 * initial) { year++; balance = balance + balance * rate / 100; }. Programa DoubleInv.java public class DoubleInv {

alvaro
Télécharger la présentation

Capitulo 6

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Capitulo 6 Iterações

  2. Ciclo while • while (condição)instruções; • Repete o ciclo enquanto a condição é verdadeira • while (balance < 2 * initial){ year++; balance = balance + balance * rate / 100;}

  3. Programa DoubleInv.java public class DoubleInv { public double getYearsDoubleInv(double rate, double initialBalance) { int year = 0; double balance = initialBalance; double interest = 0.0;

  4. // keep accumulating interest until balance // doubles while (balance < 2 * initialBalance) { year++; interest = balance * rate / 100; balance = balance + interest; } return year; } } // End Class Nota: As regras de estilo no que toca aos comentários não foram seguidas apenas por falta de espaço.

  5. Floxograma de um ciclo while

  6. Erro comum : Ciclo Infinito • while (year < 20) { balance = balance + balance * rate / 100; } • while (year > 0) { year++; . . . } • O ciclo nunca termina

  7. Ciclo for • for (init; condition; update)statement • Exemplo: for (i = 1; i <= 10; i++) ...for (y = 20; y > 0; y--) ... • Equivalente a:init;while (condition){ statement; update; }

  8. Programa Invest.java public class Invest { public double getBalance(double rate) { final double INITIAL_BALANCE = 10000; final int NYEARS = 20; double balance = INITIAL_BALANCE; double interest = 0.0;

  9. for (int year = 1; year <= NYEARS; year++) { interest = balance * rate / 100; balance = balance + interest; System.out.println("year: " + year + " balance: " + balance); } return balance; } } // End Class Nota: As regras de estilo no que toca aos comentários não foram seguidas apenas por falta de espaço.

  10. Floxograma de um ciclofor

  11. Ciclo do • doinstruções;while (condição); • Executa as instruções pelo menos uma vez • Examplo:do{ rate ++;} while (rate <= 0);

  12. Floxograma de um ciclo do

  13. Diferenças • while : repete 0 ou mais vezes • do ... while : repete 1 ou mais vezes • for : repete n vezes

  14. Erros comuns (1) • year = 0;while (balance < 2 * initial){ year++; balance = balance + balance * rate / 100;}System.out.println("Doubled after " + year + " years."); • Oyeardeve iniciar a 0 ou 1 ? • O teste deve ser<ou<= ?

  15. Erros comuns (2) • Um ponto e virgula que não deve existir sum = 0;for (i = 1; i <= 10; i++); { sum = sum + i; } System.out.println(sum); • Um ponto e virgula que falta for (i = 1; i <= 10; sum = sum + i++)System.out.println(sum);

  16. Ciclos Aninhados (1) • Tabela de potências x y 1 1 1 1 1 2 4 8 16 32 3 9 27 81 243 . . . • Exemplofor (int x = 0; x <= ROWS; x++){print row // usa outro ciclo}

  17. Ciclos Aninhados (2) • Ciclo detro de um ciclo:for (int x = 0; x <= ROWS; x++){for (int y = 0; y <= COLS; y++) {compute valueprint value}System.out.println();} • Número de ciclos:ROWS * COLS

  18. Programa Table.java public class Table { public void print() { final int COLUMN_WIDTH = 10; int p = 0; for (int x = 1; x <= 10; x++) { // print table row for (int y = 1; y <= 8; y++) { p = (int)Math.pow(x, y);

  19. // convert value to string String pstr = "" + p; // pad with spaces while (pstr.length() < COLUMN_WIDTH) { pstr = " " + pstr; } System.out.print(pstr); } System.out.println(); } } } // End Class Nota: As regras de estilo no que toca aos comentários não foram seguidas apenas por falta de espaço.

  20. “Loop and a Half” • boolean done = false;while (!done){ if (line == null) { done = true; }else {process data }}

  21. Sentinela (1) • Marcam o fim de um ciclo • Exemplo:3.52.61.20 • Ou melhor, usar uma sentinela não numérica comoQ

  22. Sentinela (2) boolean done = false;while (!done){ if (line.equalsIgnoreCase(“Q”)) { done = true; }else {process data }}

  23. Separação de Palavras • Separa a String em palavras (as palavras são delimitadas por espaços em branco) • StringTokenizer tokenizer = new StringTokenizer();while (tokenizer.hasMoreTokens()){ String token = tokenizer.nextToken();process token}

  24. Tipo de Dados : char • char: recebe um único caracter • Exemplos:'A', '\u00E9' • 'A‘ não é o mesmo que"A" • String s = . . .;for (int i = 0; i < s.length(); i++){ char ch = s.charAt(i);process ch;}

  25. Programa Reverse.java public class Reverse { public String reverse(String s) { String r = ""; char ch; for (int i = 0; i < s.length(); i++) { ch = s.charAt(i); r = ch + r; // add ch in front } return r; } } // End Class

  26. Números Aleatórios e Simulações • Gerar números aleatórios:Random generator = new Random();int n = generator.nextInt(CHOICES);double x = generator.nextDouble(); • Exemplo (gerar números entre 1 e 6)int d = 1 + generator.nextInt(6);

  27. Programa Dice.java import java.util.Random; public class Dice { public Dice() { generator_ = new Random(); } public int cast() { return 1 + generator_.nextInt(6); } private Random generator_; } // End Class

More Related