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

AI Thread Summary
The discussion centers around resolving an "Illegal start of expression" error in Java code. The primary issue identified is an unbalanced parenthesis in the while loop condition, specifically the placement of a right parenthesis that should not be there. Additionally, it highlights that using the != operator for String comparison is incorrect, as it compares object references rather than string values. Instead, the equals method should be used for proper string comparison. Another potential error noted is the risk of exceeding the length of the string when accessing it with the index j. An alternative solution is suggested, using the split method to efficiently retrieve the first word from a string, which simplifies the code and avoids the need for a loop.
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
 
Technology 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.
 


The error is here:
Code:
while (info.substring(j, j))[/color] != " ") {
That right paren shouldn't be there.
 
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"}
 

Similar threads

Back
Top