Dúvida em estrutura de controle while

1 resposta
F

Olá, pessoal. Preciso de ajuda para entender o que o while do código abaixo faz. Não entendi direito…

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

[b]// o que este while está fazendo???[/b]
  while ( row <= stars )
  {
     column = 1;
     
     // and for as many columns as rows         
     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

1 Resposta

M

Este while vai imprimir um quadrado na tela formado por *'s.
Na verdade nós temos dois laços (while) encadeados. Primeiro ele percorre linha a linha (rows), até que o número de linhas seja maior que o número de estrelas (stars), e para cada uma delas preenche a quantidade de colunas (column), também até que seja maior que o número de estrelas, com asteriscos conforme as condições (if’s), isto é, se a linha (row) for igual a 1 ou ao número de estrelas (stars) preenche com *, o mesmo vale para as colunas (column), se as condições não forem satisfeitas ele deixa o campo em branco.
Espero ter ajudado.

No site www.alberteije.com tem um curso Java Iniciante gratuito, que estou ajudando a fazer. Quem sabe o material te ajuda.

Criado 19 de outubro de 2007
Ultima resposta 21 de out. de 2007
Respostas 1
Participantes 2