简体   繁体   中英

Hollow rectangle with 3 methods

This is my code:

    int width;
    int height;

    put("Enter the width of the rectangle: ");
    width = input.nextInt();

    put("Enter the height of the rectangle: ");
    height = input.nextInt();

    rectangle( height, width );
}

public static void put(String text){
    System.out.print( text );
}

public static void put(String text, int Number){
    int plus;
    for ( plus = Number ; plus >=  1; plus-- ){
        System.out.print( text);
    }
}

public static void rectangle(int height, int width){
    int column;
    int row;

    for ( row = 1; row <= height; row++){
        put("*", width);
        put("\n");
    }
}

i want to create a hollow rectangle, and i have to modify only by the rectangle () method

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

It should be something like this ^

Any idea?

edit one

I find a way to add the first row and the last row with this code

public static void rectangle(int height, int width) {
    int column;
    int row;

    for (row = 1; row <= height; row++) {
        if (row == 1 || row == height) {
            put("*", width);
        }
        else {
            put(" ");
        }
        put("\n");
    }
}

I think that now I should control the width so I can print the two missed stars in the first and last column. I couldn't find the way to connect the rectangle method with second put method.

Any ideas please?

Try thinking of this in terms of rows and columns. In the first and last rows ( row = 1 or row = height ), you have a * in each column. In any other row, you have a * in the first and last column and a space in the rest of the columns.

As pointed out in the comments, it looks like you're putting * in each column unconditionally, but as described above you only want to do that for the first and last row.

Edit: If you want to include a blank line on even rows, here's a hint: the definition of an "even" number is "exactly divisible by 2" - think about how you could implement that in Java.

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