[英]How to convert a method from boolean to int (java)?
所以我必須用Java構建Sudoku游戲。 我可以用我的方法確認數字1到9在每一行/列中只出現一次。 但是,我將此設置為布爾值,並且無法終生弄清楚如何將其轉換為整數(以便我可以返回發生錯誤的行/列)。
public static boolean rowColumnCheck(int[][] array) {
for (int i = 0; i < 9; i++) {
boolean[] rowArray = new boolean[9];
boolean[] columnArray = new boolean[9];
for (int j = 0; j < 9; j++) {
int currentNumberRow = array[i][j];
int currentNumberColumn = array[j][i];
if ((currentNumberRow < 1 || currentNumberRow > 9)
&& (currentNumberColumn < 1 || currentNumberColumn > 9)) {
return false;
}
rowArray[currentNumberRow - 1] = true;
columnArray[currentNumberColumn - 1] = true;
}
for (boolean booleanValue : rowArray) {
if (!booleanValue) {
return false;
}
}
for (boolean booleanValue : columnArray) {
if (!booleanValue) {
return false;
}
}
}
return true;
}
你不能 每個方法基本上只有一個返回類型,並且布爾值與Integer不兼容。 如果需要返回一組坐標,則可以將返回類型更改為Integer或Pair,如果不存在則返回null。
我猜可能是這樣的。 如果為null,則沒有錯誤,並且在錯誤對上是錯誤位置。
public static Pair rowColumnCheck(int[][] array) {
Pair <Integer, Integer> p = null;
for (int i = 0; i < 9; i++) {
boolean[] rowArray = new boolean[9];
boolean[] columnArray = new boolean[9];
for (int j = 0; j < 9; j++) {
int currentNumberRow = array[i][j];
int currentNumberColumn = array[j][i];
if ((currentNumberRow < 1 || currentNumberRow > 9)
&& (currentNumberColumn < 1 || currentNumberColumn > 9)) {
p = new Pair<Integer, Integer>(i, j);
return p;
}
rowArray[currentNumberRow - 1] = true;
columnArray[currentNumberColumn - 1] = true;
}
// Not really sure why you are doing this?
for (boolean booleanValue : rowArray) {
if (!booleanValue) {
return null;
}
}
for (boolean booleanValue : columnArray) {
if (!booleanValue) {
return null;
}
}
}
return null;
}
我有一種感覺,您希望有時返回行/列對,有時返回行,有時返回列。 如果正確,那么您需要創建一個額外的類:
public class RowCol {
public final int row;
public final int col;
public RowCol(int row, int col) {
this.row = row;
this.col = col;
}
}
現在,當您要確定錯誤發生的位置時,您可以
return new RowCol(i,j);
或表示未指定列的行
return new RowCol(i,-1);
和類似的列
return new RowCol(-1,j);
方法的返回類型將為RowCol
,當您從方法中獲得返回值時,您可以查詢其row
和col
字段以找出返回值的坐標。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.