views:

167

answers:

4

I wrote this:

(fitness>g.fitness) ? return 1 : return -1;

and received the following error:

Syntax error on tokens, label expected instead.

Can anyone explain what tokens and labels are in this context?

Edit: Thanks for fixing my code, but could you explain anyway what tokens and labels are, for future reference?

+1  A: 

You need to do :

return (fitness>g.fitness) ? 1 : -1;
fastcodejava
+3  A: 

Return is a statement and ?: needs expressions and so it is not accepted.

return (fitness > g.fitness) ? 1 : -1;

is probably what you want.

When parsing the code is first split so that it is easier to understand, these units are called tokens. I guess label refers to one language construct that happens to be the first possible one in a statement.

To understand how the parser decides to give that error message would require digging into the parser. Giving good error messages from parser is not trivial.

iny
A: 

I think the compiler is telling you that since there is a colon in your code it thinks that you are trying to declare a label statement, but it can't parse it because your syntax is incorrect.

Ken Liu
+2  A: 

Tokens are the individual characters and strings which have some kind of meaning.

Tokens, as defined in Chapter 3: Lexical Structure of The Java Language Specification, are:

identifiers (§3.8), keywords (§3.9), literals (§3.10), separators (§3.11), and operators (§3.12) of the syntactic grammar.

The tokens in the given line are:

"(", "fitness", ">", "g.fitness", ")", "?", "return", "1", ":", "return", "-1", ";"

(Whitespace also counts, but I've omitted them from the above.)


Labels in Java are used for control of flow in a program, and is an identifier, followed by a colon.

An example of a label would be hello:.

Labels are used in conjunction with continue and break statements, to specify which control structure to continue or break to.

There is more information on Labeled Statements in Section 14.7 of The Java Language Specification.


The problem here is with the return statement:

(fitness>g.fitness) ? return 1 : return -1;
                      ^^^^^^

There is a : immediately following the return 1, which makes the compiler think that there is supposed to be a label there.

However, the return 1 is a statement in itself, therefore, there is no label identifier there, so the compiler is complaining that it was expecting an label, but it was not able to find a properly formed label.

(fitness>g.fitness) ?  return 1   :   return -1;
                       ^^^^^^^^   ^
                      statement   label without an identifier
coobird