集册 Java实例教程 乘法表显示

乘法表显示

欢马劈雪     最近更新时间:2020-01-02 10:19:05

359
提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
乘法表显示

import java.util.*;/**N  o w  J a v a . c o m**/


public class MultiplicationTable {


    public static void main(String[] args) throws Exception {


        int begin = 1, end = 9;


        if (args.length == 2) {

            begin = Integer.parseInt(args[0]);

            end = Integer.parseInt(args[1]);

        }


        SortedMap<Integer, List<Integer>> mt = multTable(begin, end);

        printMultiplicationTable(mt);

        System.out.println();

    }


    public static SortedMap<Integer, List<Integer>> multTable(int begin,/* 来 自 n o w j a v a . c o m*/

            int end) {


        if (begin < 0 || end < 0 || begin > end)

            return null;


        SortedMap<Integer, List<Integer>> mt = new TreeMap<>();


        for (int i = begin; i <= end; ++i) {

            List<Integer> li = new ArrayList<>();

            for (int k = begin; k <= end; ++k)

                li.add(i * k);


            mt.put(i, li);

        }


        return mt;

    }


    public static void printMultiplicationTable(

            SortedMap<Integer, List<Integer>> mt) {


        Set<Integer> keys = mt.keySet();

        Integer[] iKeys = keys.toArray(new Integer[0]);

        Integer last = iKeys[iKeys.length - 1];

        int width = Integer.toString(last * last).length() + 1;

        String fmt = "%" + width + "d";


        System.out.printf("%" + width + "s", "");

        for (Integer k : keys)

            System.out.printf(fmt, k);

        System.out.println();


        for (Integer k : keys) {

            System.out.printf(fmt, k);


            List<Integer> li = mt.get(k);

            for (Integer i : li)

                System.out.printf(fmt, i);

            System.out.println();

        }

    }

}


展开阅读全文