0
public class Square {
private final TreeMap<Integer,TreeMap<Integer,Double>> square;
private final int height;
private final int width;

public Square(int h, int w) {
    this.square = new TreeMap<>();
    this.height = h;
    this.width =  w;
} 
    public boolean isIdentity() {
    boolean isIdentity = false;
    for (Integer key1 : square.keySet()) { // First integer key of treemap (row)
        for (Integer key2 : square.keySet()) { // Second integer key (column)
            for(TreeMap<Integer, Double> value : matrix.values()) {
                if ((key1.intValue() == key2.intValue()) && (key2.intValue() == 1.0)) {
                    isIdentity = true;
                }
                else {
                    isIdentity = false;
                }
            }
        }
    }
    return isIdentity;
    }

我想看看这个正方形将成为一个身份正方形(下图)。我遇到的问题是(我认为)正确排列“键”。在我看来, (key1 / key2 ) 的双精度值应该是 1.0

身份:

1000000
0100000
0010000
0001000
0000100
0000010
0000001

(keySet() 为空?)

测试:

public static void main(String [] args) {

        HashMap<String,Square> square =
                new HashMap<String,Square>();

        Scanner input = new Scanner(System.in);
        System.out.print("Enter a command: ");
        String cmd = input.next();
        while (!cmd.equals("end")) {
            if (cmd.equals("new")) {
                String name = input.next();
                int rows = input.nextInt();
                int cols = input.nextInt();
                if (rows < 1 || cols < 1) {
                    System.out.println("new: rows and/or cols less than 1: ");
                    System.exit(1);
                }
                Square m = new Square(rows,cols);
                int i = input.nextInt();
                while (i >= 0) {
                    int j = input.nextInt();
                    double v = input.nextDouble();
                    m.set(i,j,v);
                    i = input.nextInt();
                }
                square.put(name,m);
                System.out.printf("new %s = %s\n", name, m);
            }

    if (cmd.equals("isIdentity")) {
                String which = input.next();
                if (!square.containsKey(which)) {
                    System.out.println("isIdentity: no such matrix: " + which);
                    System.exit(1);
                }
                System.out.printf("%s.isIdentity() = %b\n",
                        which, square.get(which).isIdentity());
            }

        }

    } // end of main method

测试输入如下:

Enter a command:
new one 1000 2000
   0 0 1.0
   50 834 5.0
   -1

Enter a command:
isIdentity one
4

1 回答 1

0

线

(key1.intValue() == key2.intValue()) && (key2.intValue() == 1.0)

看起来关闭。您所说的是键应该具有相同的值,并且该值也应该是 1。您可能希望第二key2.intValue()value.get(key2)代替

编辑:你也应该返回 false 而不是isIdentity = false;. 取矩阵

00
01

您的代码将首先看到 0 并设置isIdentity为 false。第二个它将 se 1 并将其设置为 true。最后它会返回 true 而不是 false 应该的。当它发现一个非单元素时,它应该立即停止,因为你知道它不可能是一个单位矩阵。

于 2013-11-15T04:39:59.940 回答