Program divisor of a number in java

2

I'm trying to do a class exercise, I'm a rookie in java and this is my second task.

The statement is this:

Make a Java program that asks the user for a whole number. After processing it, the program informs if the number is divisible by 2 or it is not

I have done this, but to put it for example 2 or 1 says that it is not a divisor, to have if you can lend me a hand of what is missing:

import java.util.Scanner;


public class operador_interrogante {


  public static void main(String[] args) {

      int num;
      byte divisor = 2;
      int division;

      Scanner teclado = new Scanner(System.in);
      System.out.println("Introduce un numero entero");
      num = teclado.nextInt();

      division = num/=divisor;

      if (divisor == division){
      System.out.println("Son divisores");
      }else{
      System.out.println("No son divisores");
      }

  }
  }
    
asked by 17.10.2018 в 11:07
source

2 answers

6

To know if a number is divisible by another it is better to use the operation module % and check that the result is 0.

if(num%2==0){
    System.out.println("Son divisores");
}else{
    System.out.println("No son divisores");
}
    
answered by 17.10.2018 / 11:20
source
0

The fault you are having is that you are comparing the result of the division with the divisor. That is, if you put a 2 you are comparing the result of 2/2, which is 1, with the divisor, which is 2. So it will always return false unless by chance the result of a division is equal to the divisor. For example 4/2 = 2, 2 == 2.

As you have said above, it is best to use% (module) to check if a number is divisible by 2.

    
answered by 17.10.2018 в 12:11