Dúvida em Estrutura de controle: while

3 respostas
fredericodf

Olá, pessoal. Não estou entendendo parte do código que está em negrito abaixo. Se alguém puder me explicar, fico agradecido. Obrigado.

import java.util.Scanner;

public class Hollow

{

// draw a hollow box surrounded by stars

public void drawHollowBox()

{

Scanner input = new Scanner( System.in );
int stars; // number of stars on a side
  int column; // the current column of the square being printed
  int row = 1; // the current row of the square being printed

  // prompt and read the length of the side from the user
  System.out.print( "Enter length of side:" );
  stars = input.nextInt();

  if ( stars < 1 )
  {
     stars = 1;
     System.out.println( "Invalid Input\nUsing default value 1" );
  } // end if
  else if ( stars > 20 )
  {
     stars = 20;
     System.out.println( "Invalid Input\nUsing default value 20" );
  } // end else if
  
  // repeat for as many rows as the user entered
  while ( row <= stars )
  {
     column = 1;
     
     // and for as many columns as rows      

   [b] // Aqui começa minha dúvida. Qual a lógica para que eu entenda 
   // o que este while fará??[/b]   
     while ( column <= stars )
     {
        if ( row == 1 )
           System.out.print( "*" );
        else if ( row == stars )
           System.out.print( "*" );
        else if ( column == 1 )
           System.out.print( "*" );
        else if ( column == stars )
           System.out.print( "*" );
        else
           System.out.print( " " );

        column++;
     } // end inner while loop

     System.out.println();
     row++;
  } // end outer while loop

} // end method main
} // end class Hollow


Minha dúvida: Quero entender a lógica da tarefa do while neste código.

3 Respostas

Pedro_Java

Enquanto o valor logico dentro do () for verdadeiro ele vai ficar fazendo as interaçoes, imagine como se fosse um “for” no seu caso, ele faz oq tem q fazer incrementa o column depois verifica se c eh menor q o stars, c continuar menor ele vai continuar fazendo, ateh q o valor seja maior pq ateh menor igual ele aceita! Ok?

F

O laço irá se repetir enquanto a condição column <= stars for verdadeira…

Enquanto isto ocorrer, o valor das variáveis row e column são analisados e dependendo do resultado da comparação, um ou outro bloco if irá ser executado…

Certo?

F

Ah… agora ficou melhor de se entender. Fernandoeik e pedro java:

Obrigado pela explicação. Valeu mesmo!

Criado 19 de outubro de 2007
Ultima resposta 20 de out. de 2007
Respostas 3
Participantes 4