Reputation: 17
I need to create a program that reads 2 integers from the keyboard and prints a message saying whether the first number divides the second evenly.
I know I have to use either / or %, but it's not working.
int y, x,z;
System.out.print("Enter first number: ");
x= keyboard.nextInt();
System.out.print("Enter second number: ");
y= keyboard.nextInt();
z=y/x;
if (z%2==0){
System.out.println("Divides evenly");
} else {
System.out.println("Does not divide evenly");
}
I have to divide y by x. So, for example, x= 25 y=100, it should come out even. Then x=35 y=100 not even.
I've tried
z==0
z%y==0
Not working.
Upvotes: 1
Views: 7134
Reputation: 18177
You're close, you don't need the extra integer division.
Integer division ( %
) gives you the remainder. So when you do z=y%x;
, all you need to do in your if
statement is check that z
is equal to 0
(meaning that the first number evenly decided the second number).
int y, x,z;
System.out.print("Enter first number: ");
x= keyboard.nextInt();
System.out.print("Enter second number: ");
y= keyboard.nextInt();
z=y%x;
if (z==0){ //Changed this liine
System.out.println("Divides evenly");
} else {
System.out.println("Does not divide evenly");
}
Upvotes: 3
Reputation: 36
int x,y;
System.out.print("Enter first number: ");
x= keyboard.nextInt();
System.out.print("Enter second number: ");
y= keyboard.nextInt();
if (x%y==0){
System.out.println("Divides evenly");
} else {
System.out.println("Does not divide evenly");
}
Upvotes: 1