-1

嘿,我有一个包含多个值的 LinkedHashMap,但我正在努力以我想要的格式打印它。它将传递一个大小整数,我希望它以方形格式打印出值,如果某个键的值不超过大小值,则将 0 放在那里。

假设这些是哈希图中的值,第一个是位置,第二个是值

hashmap.put(1, 10); 
hashmap.put(2, 90); 
hashmap.put(4, 9); 
hashmap.put(7, 2); 
hashmap.put(11, 4); 
hashmap.put(14, 45); 

我希望它在传递值 4(高度/宽度)后打印如下。

0 10 90 0
9 0  0  2
0 0  0  4
0 0  45 0

对不起,这个描述真的很糟糕,不知道怎么说更好!为任何帮助而欢呼。

4

3 回答 3

2

如果给定一个整数 n,并且您正在迭代从 0 到 n^2 的整数。在循环中,您可以使用 mod 来确定您是否是行尾。

       if((i mod n) == 0){
           //print a new line here
       }

因此,只需编写一个从 0 到 n^2 的循环,并使用该 if 语句来知道何时中断到下一行。

于 2013-03-09T19:33:52.937 回答
2
public static void printMapAsMatrix(Map<Integer, Integer> map, int size) {
    for (int i = 0; i < size; i++) {
        for (int j = 0; j < size; j++) {
            Integer v = map.get(size * i + j);
            if (v == null)
                v = 0;
            System.out.printf("%1$-5s", v);
        }
        System.out.println();   
    }
}

此解决方案填充每个单元格,使其占用 5 个字符。如果需要,您可以更改此设置。这个想法是通过扫描所有单元格 (0..size-1)x(0..size-1) 并从地图中获取该单元格的值来创建完整矩阵。第 i 行和第 j 列应该转换为 key=size * i + j,因为我们必须跳过当前行中的 i 行和 j 项。不存在的项目被转换为 0。

于 2013-03-09T19:38:23.543 回答
0
public static void main(String[] args) {

        Map<Integer, Integer> hashmap = new HashMap<Integer, Integer>();
        hashmap.put(1, 10);
        hashmap.put(2, 90);
        hashmap.put(4, 9);
        hashmap.put(7, 2);
        hashmap.put(11, 4);
        hashmap.put(14, 45);

        printSquare(4, hashmap);
    }

    public static void printSquare(int dimension, Map<Integer,Integer> map){
        int grid = dimension * dimension;

        for(int x = 0; x < grid; x++){

            Integer value = map.get(x);
            value = (value == null) ? 0:value;

            if(x != 0 && x % 4 == 0){
                System.out.println("\n");
                System.out.print(value);
                System.out.print("\t");
            }else{
                System.out.print(value);
                System.out.print("\t");
            }
        }
    }
于 2013-03-09T19:42:47.520 回答