Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

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

  1. Feb 27, 2013 #1
    [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
     
  2. jcsd
  3. Feb 27, 2013 #2

    jbunniii

    User Avatar
    Science Advisor
    Homework Helper
    Gold Member

    Re: Can't figure out this "Illegal start of expression" error

    Assuming this is a verbatim copy/paste from your code, you seem to have an unbalanced parenthesis.
     
  4. Feb 27, 2013 #3
    Re: Can't figure out this "Illegal start of expression" error

    Wow. I'm an idiot.
     
  5. Feb 27, 2013 #4

    Mark44

    Staff: Mentor

    Re: Can't figure out this "Illegal start of expression" error

    The error is here:
    Code (Text):
    while (info.substring(j, j)[color="red"])[/color] != " ") {
     
    That right paren shouldn't be there.
     
  6. Feb 27, 2013 #5
    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.
     
  7. Feb 28, 2013 #6

    Borg

    User Avatar
    Science Advisor
    Gold Member

    Re: Can't figure out this "Illegal start of expression" error

    You are also going to hit an error when the value of j is larger than the length of info.
     
  8. Mar 1, 2013 #7
    Re: [Java] Can't figure out this "Illegal start of expression" error

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

    Code (Text):

    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"}
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook




Similar Discussions: [Java] Can't figure out this Illegal start of expression error
Loading...