[Java] Can't figure out this Illegal start of expression error

Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
6 replies · 3K views
Jamin2112
Messages
973
Reaction score
12
[Java] Can't figure out this "Illegal start of expression" error

From my Java code:

while (info.substring(j, j)) != " ") {
name += info.substring(j, j);
j++;
}

gives an "illegal start of expression" error
 
Physics news on Phys.org


Jamin2112 said:
From my Java code:

while (info.substring(j, j)) != " ") {
name += info.substring(j, j);
j++;
}

gives an "illegal start of expression" error

Assuming this is a verbatim copy/paste from your code, you seem to have an unbalanced parenthesis.
 


jbunniii said:
Assuming this is a verbatim copy/paste from your code, you seem to have an unbalanced parenthesis.

Wow. I'm an idiot.
 
Can't figure out this "Illegal start of expression" error

One other thing to note: != is not doing what you probably want for Strings. Strings aren't a primitive type in Java, so the != operator is comparing the objects references. That operation evaluates to true only if the two strings are not the same object. You should use the equals method: !a.equals(b) to test if the value of the strings a and b are not equal.
 


gbeagle said:
One other thing to note: != is not doing what you probably want for Strings. Strings aren't a primitive type in Java, so the != operator is comparing the objects references. That operation evaluates to true only if the two strings are not the same object. You should use the equals method: !a.equals(b) to test if the value of the strings a and b are not equal.
You are also going to hit an error when the value of j is larger than the length of info.
 


Also an alternative simpler way to do the same thing without looping is:

Code:
name = info.split(" ")[0];

The split function will split the String on " " returning an array of Strings. Getting the first element in the array gives you everything up to the first space.

(Ex: if info is "foo bar baz" then info.split(" ") returns {"foo", "bar", "baz"}