java question about condition ? expr. : expr.

March 3, 2010 at 07:30:28
Specs: Macintosh
* Why do i get a error.
* My java editor (Eclipse) says i should change the type of num to bolean.
* Which is not what i want and "isNumberPrime(int num)" returns a boolean.
* It's a complete mystery to me.
* code snippet:
* isNumberPrime(num) ? println(num + " is a prime") : println(num + " is not a prime");

See More: java question about condition ? expr. : expr.

Report •

March 3, 2010 at 23:33:32
I don't know JAVA or its particulars, but it *looks* like you aren't testing against anything.

IsNumberPrime(num) returns either true or false, so your statement would behave as

TRUE ? A : B


IsNumberPrime(num) == TRUE ? A : B;

Report •

March 4, 2010 at 00:33:03
I'm not sure why you are getting an error. Without testing it, I
would guess one of two things. First, are you absolutely sure
your IsNumberPrime method takes an int and returns a
boolean? Maybe you have an overloaded method of the same
name that returns something else? If it returns a boolean,
then that's what is needed left of the "?" .

Another point is that this construct is just two operators that
yield an expression, but what is the type of the expression?
Println returns void. If you don't want to take the value of the
expression, just use if/else.

Alternatively, put the ?: expression inside the println call. The
expression will be the argument to println, and will give you a
string, whose value depends on whether the number is prime.

Report •

March 5, 2010 at 05:35:53
klint, thanks for your reply.
The thing i don't understand is that when i put the same IsNumberPrime in a if like: [code] if (IsNumberPrime(num)) {println("println(num + " is a prime")} else {println(num + " is not a prime")};[\code] i get the result i want, but in the ? : form i get the error.

Report •

Related Solutions

March 5, 2010 at 09:40:43
Couple of questions to help me understand your problem.

1. What is the exact error message you get from the compiler
- please copy & paste.

2. Where is println defined? (Normally you need to type out
the full name System.out.println - have you defined your own
println method?)

Report •

Ask Question