鉴于多米诺骨牌的安排,确定它是否是一种法律安排,并相应地返回真或假。例如,这是一项非法安排[2 3] [4 2] [2 2] [3 5],这是多米诺的法律安排。 [2 3] [3 5] [5 4] [4 5]。
这是我现在的编码,但我希望它在合法时非法和合法时输出非法。有没有办法在编码和出局中安排哪些是非法的,哪个是合法的?
public class Domino {
private int leftValue;
private int rightValue;
public Domino(int leftValue, int rightValue) {
this.leftValue = leftValue;
this.rightValue = rightValue;
}
public int getLeftValue() {
return leftValue;
}
public int getRightValue() {
return rightValue;
}
public static void main(String[] args) {
// This creates the Array
Domino[] dominos = new Domino[] {
new Domino(2, 3),
new Domino(3, 2),
new Domino(2, 5),
new Domino(2, 5)
};
// This part Loops and matchs left and right values
Domino previous = null;
for (Domino current : dominos) {
if (previous != null) {
if (current.getLeftValue() != previous.getRightValue()) {
try {
throw new Exception("Illegal");
} catch (Exception e) {
e.printStackTrace();
}
}
}
previous = current;
}
}
}
答案 0 :(得分:0)
您可以尝试使用以下代码替换for
循环:
for (Domino current : dominos) {
if (previous != null) {
if (current.getLeftValue() != previous.getRightValue()) {
System.out.println("[" + previous.getLeftValue() + " " + previous.getRightValue()
+ "][" + current.getLeftValue() + " " + current.getRightValue() + "] is illegal");
} else {
System.out.println("[" + previous.getLeftValue() + " " + previous.getRightValue()
+ "][" + current.getLeftValue() + " " + current.getRightValue() + "] is legal");
}
}
previous = current;
}