简体   繁体   中英

Solid rectangle not printing correctly in java

I am looking for a solid rectangle made by asterisk marks. 4 rows and 5 columns.

My code:

public class class5 {
    public static void main(String args[]) {

        
        //solid rectangle
        
        int n = 4;
        var m = 5;


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

When I run this code, I get asterisks printing endlessly. Please help me with the same. Thanks in advance.

We need to print " " whenever j is more than 1 and less than m except for the scenarios when i is 1 or n

public class Class5 {
    public static void main(String args[]) {
        //solid rectangle
        int n = 5;
        int m = 4;

        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= m; j++) {
                if(j>1 && j<m && i!=1 && i!=n){
                    System.out.print(" ");
                }else {
                    System.out.print("*");
                }
            }
            System.out.println();
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM