How to make a rectangle of asterisks using for?

Asked

Viewed 2,418 times

4

To solve this exercise:

Write a program that prints a rectangle of n x m asterisks, in the which values of n and m are provided 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 Rectangloasteriscos { 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 of the example, the rectangle of my program comes out like this:

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

How to solve this?

  • The rule is a for to repeat lines and an internal one concatenating each asterisk with the same amount of for

  • 1

    Is there any restriction on using the standard library?

3 answers

3


Only with a bow, you can do it this way:

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:

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

Functioning in the ideone: https://ideone.com/OwdYjk


Reference:

Printing a Square with loops

2

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

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();
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.