A
number x is divisible by y if the remainder after the division is zero. Write
a
program that tests whether one number is divisible by another number. Reads
both numbers from the keyboard.
public static void divisible() {
Scanner
kb = new Scanner(System.in);
System.out.println("Enter
the value of x...");
int x = kb.nextInt();
System.out.println("Enter
the value of y...");
int y = kb.nextInt();
if (x % y == 0) {
System.out.println(x + " is
divisible by " + y);
}
else {
System.out.println(x + " is not
divisible by " + y);
}
}
Code explanation:
public static void divisible(): Here the void we use void method because it won't return, but print a result.
public static void divisible(): Here the void we use void method because it won't return, but print a result.
Scanner kb = new Scanner(System.in): In this program we're going to read two integers from the keyboard. Scanner is used with this objetive. Note: In order to utilize Scanner we need to import the Scanner library. We must include the following line of code: import java.util.Scanner.
System.out.println("Entrar un numero x..."): System.out.println prints a message though the console. In this case to give instructions to the user.
int x = kb.nextInt(): Here we declare the variable x as an int, which is equals to the variable kb that we declared in Scanner. nextInt() means it is going to take the next Integer value the user enter through the keyboard and is going to be stored at the variable x.
Then we repeat the code for variable y.
if (x % y == 0): In order to get the remainder from the division between two numbers we use the Mod method. In Java it is represented by the percentage sign (%).
The rest of the code prints if either x is divisible by y or no.
0 Comments:
Post a Comment