Home > front end >  Beginner question, incompatible types: boolean to int. Not seeing the problem
Beginner question, incompatible types: boolean to int. Not seeing the problem

Time:10-03

Trying to find out if any of the digits in a number are odd, if so return true. If any are even then return false. Getting error: incompatible types: boolean cannot be converted to int. Any help is appreciated.

public class allDigitsOddTest{

     public static void main(String[] args) {
     allDigitsOdd(756410);
     }

    public static int allDigitsOdd(int num){
        boolean value = true;
        int evens = 0;
        int odds = 0;
        
        while (num > 0){
            int remainder = num % 10;
            
            if (remainder % 2 == 0){
                evens  ;
            }
            else{
                odds  ;
            }   
            num = num / 10; 
        } 
        if (evens > 0){
            value = false;
        }
        return value;
    }

}

CodePudding user response:

Your return type is int, instead of boolean

change

 public static int allDigitsOdd(int num) 

to

public static boolean allDigitsOdd(int num)  {

CodePudding user response:

In the beginning it helped me a lot to look at Methods like this:

You try to unlock your door at home, which you have the keys for. It doesn't matter which of your three keys you use, because it works with every one of your keys. But if you try your car key it won't fit and the mission is a failure.

So look at the different data types as keys, you can lock the door with your main key, and your girlfriend unlocks it later with hers. -> One key in, another one of the same out if you understand what I mean.

Same for Java, you give an integer into the method, you can return every integer you want, but not a different data type (or key type).

Maybe an odd example, but for some reason it helped me a lot.

  •  Tags:  
  • java
  • Related