Reputation: 19
Hoping that this one doesn't cause much trouble in answering, but when writing this out in my Sudoku project, I knew there must be a better way of phrasing this if condition.
Thanks in advance guys.
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);
}
}
Upvotes: 2
Views: 758
Reputation: 21975
If you're using java 8, there is a way using an IntStream
. The advantage is that you could use this with any number of parameters.
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);
}
}
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.
Upvotes: 6
Reputation: 6473
You could pull out the logic into Boolean values and just test those instead e.g.
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);
}
Or, given that the limits are identical for each (row, column and value all inclusively 1-9), then you could extract that to a method called withinLimits(value)
that checks for the value being between 1 and 9.
public boolean withinLimits(int value) {
return value >= 1 && value <= 9;
}
Then...
if (withinLimits(r) && withinLimits(c) && withinLimits(x)) {
sudoku.set(r, c, x);
}
Not a great deal better than what you have though, just a little more terse syntactically speaking. And you don't require the additional parentheses either. Just drop them.
Upvotes: 7