Saturday, June 21, 2014

Java Exercise Nr. 40 (Selections)

Write a program that prompts the user to enter an integer and determines whether it is divisible by 5 and 6, whether it is divisible by 5 or 6, and whether it is divisible by 5 or 6, but not both.

Solution:

public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int number;

System.out.print("Enter a number:");
number = s.nextInt();

System.out.print("Is " + number + " divisible by 5 and 6?");
if((number % 5 == 0) && (number % 6 == 0)) {
System.out.println(" true");
} else {
System.out.println(" false");
}

System.out.print("Is " + number + " divisible by 5 or 6?");
if((number % 5 == 0) || (number % 6 == 0)) {
System.out.println(" true");
} else {
System.out.println(" false");
}

System.out.print("Is " + number + " divisible by 5 or 6, but not both?");
        // XOR operator for the third condition
if((number % 5 == 0) ^ (number % 6 == 0)) {
System.out.println(" true");
} else {
System.out.println(" false");
}
}

No comments:

Post a Comment

Author