Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.example.oop.multiplication;
- import java.util.Arrays;
- import java.util.Scanner;
- import static java.util.stream.Collectors.joining;
- class MultiplicationTable {
- private final int size;
- public MultiplicationTable(int size) {
- this.size = size;
- }
- public int[][] content() {
- if (size <= 0) {
- throw new IllegalArgumentException(String.format("Size must be positive, but is: %d", size));
- }
- int[][] result = new int[size][size];
- for (int row = 0; row < size; ++row) {
- for (int col = 0; col < size; ++col) {
- result[col][row] = (row + 1) * (col + 1);
- }
- }
- return result;
- }
- }
- class FromString implements PositiveInteger {
- private final String string;
- public FromString(String string) {
- this.string = string;
- }
- @Override
- public int get() {
- Integer parsed = Integer.valueOf(string);
- if (parsed <= 0) {
- throw new IllegalArgumentException("Value is not positive: " + parsed);
- }
- return parsed;
- }
- }
- class IntMatrix {
- private final int[][] body;
- public IntMatrix(int[][] body) {
- this.body = body;
- }
- @Override
- public String toString() {
- return Arrays.stream(body).map(this::printRow).collect(joining("\n"));
- }
- private String printRow(int[] row) {
- return Arrays.stream(row).mapToObj(String::valueOf).collect(joining(" "));
- }
- }
- interface PositiveInteger {
- int get();
- }
- class MultiplicationTableApp implements Runnable {
- @Override
- public void run() {
- Scanner scanner = new Scanner(System.in);
- boolean success = false;
- do {
- System.out.println("Enter size:");
- String userInput = scanner.nextLine();
- PositiveInteger size;
- try {
- size = new FromString(userInput);
- System.out.println(new IntMatrix(new MultiplicationTable(size.get()).content()).toString());
- success = true;
- } catch (IllegalArgumentException exception) {
- System.out.println("Invalid input: " + exception.getMessage());
- System.out.println("Try again");
- }
- } while (!success);
- }
- }
- public class App {
- public static void main(String[] args) {
- new MultiplicationTableApp().run();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment