I have an assignment/project to write a program that displays the integers between 1 and 100 that are divisible by 6 or 7, but not both. It does not work the way I’ve written it below. Is my boolean value correct for what the question is asking?
import acm program.*;
public class SixAndSeven extends ConsoleProgram {
public void run() {
for (int n = 1; n < 100; n++) {
boolean year = (n % 6 ==0) ||
(n % 7 ==0) &&
!(n % 6 == 0) &&
( n % 7 ==0);
if (year) {
println(year);
}
}
}
}
You should do the below
Basically group the 2 sets of conditions within a
()before negating, so that the conditions apply correctly to both.To make it more readable, you could do this.. (though perhaps overkill..)
or the clever method suggested by Mel (possibly harder to understand at a glance), which returns
trueonly if one but not both conditions are true.P.S. Additionally, as user1333371 suggests, you probably want to do
println(n);