Страницы

Поиск по вопросам

вторник, 28 января 2020 г.

Помогите упростить функцию

#java


Помогите упростить функцию drawRect(int w, int h);. Понимаю, костыли за костылями,
но на ошибках учатся. Мне важны какие то специальные методы для упрощения.

package com.company;

public class Main {

    public static void drawRect(int w, int h) {
        for (int i = 0; i < w; i++) {
            if (i == 0)
                System.out.print("╔");
            else if (i == (w - 1))
                System.out.print("╗");
            else
                System.out.print("═");
        }
        System.out.print("\n");
        for (int i = 0; i < h; i++) {

            if (i != h - 1) {
                System.out.print("║");
                for (int j = 0; j < (w - 2); j++) {
                    System.out.print(" ");
                }
                System.out.println("║");
            }
            else {
                System.out.print("╚");
                for (int j = 0; j < (w - 2); j++) {
                    System.out.print("═");
                }
                System.out.println("╝");
                }
        }
    }
    public static void main(String[] args) {
        drawRect(30, 10);
    }

}


На выходе рисует

╔════════════════════════════╗
║                            ║
║                            ║
║                            ║
║                            ║
║                            ║
║                            ║
║                            ║
║                            ║
║                            ║
╚════════════════════════════╝

    


Ответы

Ответ 1



В примитивном виде: public static String stringRepeat(String str, int times) { return new String(new char[times]).replace("\0", str); } public static void drawRect(int w, int h) { System.out.print("╔"); System.out.print(stringRepeat("=", w - 2)); System.out.println("╗"); for (int i = 0; i < h - 2; i++) { System.out.print("║"); System.out.print(stringRepeat(" ", w - 2 )); System.out.println("║"); } System.out.print("╚"); System.out.print(stringRepeat("=", w - 2)); System.out.println("╝"); } Далее вместо множества System.out можно загонять с помощью StringBuilder в отдельную переменную и в конце вывести Для string.repeat можно использовать apache StringUtils

Ответ 2



Я бы завёл матрицу символов, которую бы сначала заполнил, а потом вывел. Это будет дольше работать и требует дополнительной памяти (и кода, возможно, получится больше), но зато, как мне кажется, это гораздо понятней и поддерживать такой код проще. Код на ideone. public class Main { public static void drawRect(int w, int h) { char[][] matrix = new char[h][w]; // углы matrix[ 0][ 0] = '╔'; matrix[ 0][w - 1] = '╗'; matrix[h - 1][ 0] = '╚'; matrix[h - 1][w - 1] = '╝'; // левая и правая сторона for (int i = 1; i < h - 1; ++i) { matrix[i][ 0] = '║'; matrix[i][w - 1] = '║'; } // левая и правая сторона for (int j = 1; j < w - 1; ++j) { matrix[ 0][j] = '═'; matrix[h - 1][j] = '═'; } // пробелы for (int i = 1; i < h - 1; ++i) { for (int j = 1; j < w - 1; ++j) { matrix[i][j] = ' '; } } // вывод for (int i = 0; i < h; ++i) { for (int j = 0; j < w; ++j) { System.out.print(matrix[i][j]); } System.out.println(); } } public static void main(String[] args) throws Exception { drawRect(30, 10); } }

Ответ 3



Можно вынести лишние проверки из циклов, а также объявить пару констант: ширину и высоту. public static void drawRect(int w, int h) { final int width = w - 2; final int height = h - 2; System.out.print("╔"); for (int i = 0; i < width; i++) { System.out.print("═"); } System.out.println("╗"); for (int i = 0; i < height; i++) { System.out.print("║"); for (int j = 0; j < width; j++) { System.out.print(" "); } System.out.println("║"); } System.out.print("╚"); for (int j = 0; j < width; j++) { System.out.print("═"); } System.out.println("╝"); } Также можно вынести в отдельные функции рисование верхней/средней и нижней линий.

Комментариев нет:

Отправить комментарий