tay*_*anu 2 java methods if-statement
希望这个问题在回答时不会造成太大麻烦,但是当我在我的数独项目中写出来时,我知道必须有一个更好的方法来表达这个条件.
先谢谢你们.
public static void modVal(int r, int c, int x) {
if((r>=1 && r<=9) && (c>=1 && c<=9) && (x>=1 && x<=9)) {
sudoku.set(r,c,x);
}
}
Run Code Online (Sandbox Code Playgroud)
您可以将逻辑拉出为布尔值,然后测试它们,例如
boolean validRow = r >= 1 && r <= 9;
boolean validColumn = c >= 1 && c <= 9;
boolean validValue = x >= 1 && x <= 9;
if (validRow && validColumn && validValue) {
sudoku.set(r, c, x);
}
Run Code Online (Sandbox Code Playgroud)
或者,假设每个(行,列和值都包含1-9)的限制相同,那么您可以将其提取到一个名为的方法withinLimits(value),以检查介于1和9之间的值.
public boolean withinLimits(int value) {
return value >= 1 && value <= 9;
}
Run Code Online (Sandbox Code Playgroud)
然后...
if (withinLimits(r) && withinLimits(c) && withinLimits(x)) {
sudoku.set(r, c, x);
}
Run Code Online (Sandbox Code Playgroud)
虽然没有比你所拥有的更好,但从语法上来说只是一点点简洁.而且您也不需要额外的括号.放下它们吧.
如果你使用的是java 8,有一种方法可以使用IntStream.优点是您可以使用任意数量的参数.
public static void modVal(int r,int c,int x){
if (IntStream.of(r,c,x).allMatch(i -> i>=1 && i<=9)) {
sudoku.set(r,c,x);
}
}
Run Code Online (Sandbox Code Playgroud)
Instream.of(r,c,x) // This will just stream over the data given in parameters.
.allMatch(Predicate) // This will return true if all the data entered as parameter has been tested within Predicate and returned true.
Run Code Online (Sandbox Code Playgroud)