Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java Java Objects (Retired) Creating the MVP Comparing Characters

Matt O'Connor
Matt O'Connor
1,705 Points

How to retrieve the first character in a string and compare it

Hi there,

The solution to this problem suggests that we need to compare chars using the < and > operators however we only have a string as an argument to the method.

I've re-watched the previous lecture and can't see that it was explained how to get the first character from a string, store it in a char and compare it. The indexOf method returns a type of int, so we can't for example do char firstCharacter = lastName.indexOf(0); Also I can't see that a boolean check from the lecture is appropriate as that was a check for a character at any point in the string whereas we need to check the character at the first index.

Can anyone help with my thinking to solve this problem?

Many thanks,

1 Answer

You need to set the value of the variable line to 1 if the last name starts with an M, otherwise to 2. The easiest way to see if a String starts with a particular letter is to use charAt(0), which returns the first letter (the first char) in the String. (Think of Strings as a collection of chars.) As the challenge says, you can use the comparative operators <, >, etc. to compare chars. This code compares the first letter (the first char) to M. If the char is less than M it assigns the person to the first line. Otherwise it assigns the person to the second line.

  public int getLineFor(String lastName) {
    /* If the last name is between A thru M send them to line 1
       Otherwise send them to line 2 */
    int line = 0;
    if (lastName.charAt(0) < 'M') {
      line = 1;
    } else {
      line = 2;
    }
    return line;
  }
Matt O'Connor
Matt O'Connor
1,705 Points

Thanks for this. The problem was I went to log into treehouse to resume my course and it skipped the lecture where this was explained for some reason and went straight to the exercise.

It's all good now and thanks for your answer.