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