Incompatible types - cannot call method to check int.
Hello!
I'm currently working on a prime number checker as well as an prime number adder, but i can't seem to get them to function properly.
I have written them in BlueJ, since I'm a newbie, and in different methods, in case I need the prime checker later on. What I want to do is check for all the primes below a value, in my case 10, and then sum these and print the value.
Here be some code:
Code:
/**
* A basic brute-force prime checker.
*/
public void isPrime(int primeCheck){
int x = primeCheck;
int y =2;
while(x>y){ //while x>y works
if((x%y) !=0){
y++;
}else{
System.out.println("not a prime");
y=x;
}
}
}
/**
* Basic add prime numbers, utilizing isPrime()
*/
public void primesBelow(){
int x=2;
for(int i=3;i<10;i++){
if(isPrime(i)){
x+=i;
}
}
System.out.println(x);
}
When I try to compile, it states "incompatible types" and leaves me befuddled. Isn't isPrime
supposed to accept int as input? Please, explain to me what I'm doing wrong.
Regards/ ts
Re: Incompatible types - cannot call method to check int.
That's not your problem. It does take an int. The problem is that if(...) expects a boolean (true or false), and isPrime returns void, not boolean.
Re: Incompatible types - cannot call method to check int.
Oh, I see. Is this a matter of changing the return type of isPrime, or can I refrase the if in terms of if(isPrime== something clever) which evaluates to true and then get the expected result?
Re: Incompatible types - cannot call method to check int.
No, you cannot compare the return value of isPrime since it doesn't return anything but void. Regardless of whether the value passed in is prime or not, it still returns void.
Instead make the method return boolean
Code:
public boolean isPrime(int check){...}
Then modify the code to return true or false in the correct position rather than printing stuff.
Re: Incompatible types - cannot call method to check int.
Of course!
Needless to say, you've made me progress a little further in terms of understanding Java.
Thanks a lot.
Re: Incompatible types - cannot call method to check int.
You are welcome, I am glad to have helped.