Как напечатать математическую таблицу умножения, возвращающую значение String в матрице 2x2 и 3x3, используя вложенные циклы в Java - PullRequest
1 голос
/ 07 апреля 2020

Я пытаюсь получить метод, который возвращает следующую строку для целочисленного параметра 2:

Вывод:

enter image description here

То же самое для параметра 3

enter image description here

Код, который я получил до сих пор, находится ниже:

public String simpleMultiplicationTable(int num) {
    for(int i = 1 ;i<=num;i++) {
        for(int j=1;j<=num;j++) {
            System.out.format("%4d",i*j);
        }
        System.out.println();
    }
    return String.valueOf(num);      
}

1 Ответ

0 голосов
/ 07 апреля 2020

Вместо того, чтобы печатать каждое значение, добавьте его к StringBuilder и верните его в конце.

Сделайте это следующим образом:

public class Main {
    public static void main(String[] args) {
        // Tests
        System.out.println(simpleMultiplicationTable(2));
        System.out.println(simpleMultiplicationTable(3));
    }

    public static String simpleMultiplicationTable(int num) {
        StringBuilder sb = new StringBuilder();
        for (int i = 1; i <= num; i++) {
            for (int j = 1; j <= num; j++) {
                sb.append(i * j);
                if (j < num) {
                    sb.append(" ");
                }
            }
            if (i < num) {
                sb.append("\n");
            }
        }
        return sb.toString();
    }
}

Вывод:

1 2
2 4
1 2 3
2 4 6
3 6 9

Использование String вместо StringBuilder:

public class Main {
    public static void main(String[] args) {
        // Tests
        System.out.println(simpleMultiplicationTable(2));
        System.out.println(simpleMultiplicationTable(3));
    }

    public static String simpleMultiplicationTable(int num) {
        String table = "";
        for (int i = 1; i <= num; i++) {
            for (int j = 1; j <= num; j++) {
                table += j < num ? i * j + " " : i * j;
            }
            if (i < num) {
                table = table + "\n";
            }
        }
        return table;
    }
}

JUnit Tests

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;

import org.junit.jupiter.api.Test;

class TestMethods {

    @Test
    public void testSimpleMultiplicationTable() {
        Table table = new Table();
        String result = table.simpleMultiplicationTable(2);
        if (result.contains(" \n")) {
            fail("Your output table has one or more extra spaces before the newline character. You can use the trim() function to remove additional spaces");
        }
        assertEquals("1 2\n2 4", result);

        result = table.simpleMultiplicationTable(1);
        if (result.contains(" \n")) {
            fail("Your output table has one or more extra spaces before the newline character. You can use the trim() function to remove additional spaces");
        }
        assertEquals("1", result);
    }
}

class Table {

    public String simpleMultiplicationTable(int num) {
        String table = "";
        for (int i = 1; i <= num; i++) {
            for (int j = 1; j <= num; j++) {
                table += j < num ? i * j + " " : i * j;
            }
            if (i < num) {
                table = table + "\n";
            }
        }
        return table;
    }
}
...