How to make a rectangle of asterisks using for?

4

To resolve this exercise:

  

Write a program that prints a rectangle of n x m asterisks in the   which values of n and m are supplied by the user. For example,   for values of n = 5 and m = 7, the expected result is:

     

******* -
  ******* -
  ******* -
  ******* -
  ******* -

I made this code:

import java.util.Scanner;

public class RetanguloAsteriscos { public static void main(String[] args) { int m, n;

Scanner teclado = new Scanner(System.in); n = teclado.nextInt(); m = teclado.nextInt(); for (int i=1 ; i <= n ; i++) { System.out.println("*"); } for (int j=1 ; j <= m ; j++) { System.out.print("*"); }

It turns out that I did not get the expected result, using the same values as the example, the rectangle of my program goes like this:

  

* -
  * -
  * -
  * -
  * -
  ******* -

How to solve this?

    
asked by anonymous 27.05.2017 / 21:39

3 answers

3

Only with a loop, you can do this:

int linhas = 4;
int colunas = 7;

for (int i = 0; i < colunas; i++) {
    System.out.print("*");
}

System.out.println();

for (int i = 0; i < linhas - 2; i++) {

    System.out.print("*");

    for (int j = 0; j < colunas - 2; j++) {
        System.out.print("*");
    }

    System.out.println("*");
}

for (int i = 0; i < colunas; i++) {
    System.out.print("*");
}

System.out.println();

Result with columns = 7 and rows = 4:

*******
*******
*******
*******

Running on ideone: link

Reference:

Printing a Square with loops

    
27.05.2017 / 22:05
1
Scanner teclado = new Scanner(System.in);
int n = teclado.nextInt();
int m = teclado.nextInt();
int temp = m;
for( ; n > 0 ; n-- ){
   for( temp = m; temp > 0 ; temp-- ){
      System.out.print("*");
   }
   System.out.println();
}
    
29.05.2017 / 17:28
1

With for you could do something like:

int colunas = 7, linhas = 4;

for(int l = 0; l < linhas; l++){
    for(int c = 0; c < colunas; c++){
        System.out.print("*"); // colunas
    }
    System.out.println(); // linhas
}

output:

*******
*******
*******
*******

Ideone Example

    
29.05.2017 / 20:09