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) Delivering the MVP Validation

Charlie Gallentine
Charlie Gallentine
934 Points

Validation throwing IllegalArgumentException

Why does mFirstName get caught on the second if block in this code? I am struggling to understand why it trips the exception.

Thank you!

TeacherAssistant.java
public class TeacherAssistant {

  public static String validatedFieldName(String fieldName) {
    // These things should be verified:
    // 1.  Member fields must start with an 'm'
    // 2.  The second letter in the field name must be uppercased to ensure camel-casing
    // NOTE:  To check if something is not equal use the != symbol. eg: 3 != 4
    if (fieldName.charAt(0) != 'm') {
      throw new IllegalArgumentException("Must be m");
    }

    if (! Character.isUpperCase(fieldName.indexOf(1))) {
      throw new IllegalArgumentException("must be upper case");
    }
    return fieldName;
  }

}

2 Answers

Stone Preston
Stone Preston
42,016 Points

Use the charAt method, not indexOf. indexOf returns the index of a specific character in the string. charAt returns the character at the specified index

We want to check if the second character in the string (index 1) is uppercase, so we call the charAt method and pass in 1 to get what that character is, then check if its uppercase

public class TeacherAssistant {

  public static String validatedFieldName(String fieldName) {
    // These things should be verified:
    // 1.  Member fields must start with an 'm'
    // 2.  The second letter in the field name must be uppercased to ensure camel-casing
    // NOTE:  To check if something is not equal use the != symbol. eg: 3 != 4
    if (fieldName.charAt(0) != 'm') {
      throw new IllegalArgumentException("Must be m");
    }

    // use charAt(1), not indexOf(1)
    if (!Character.isUpperCase(fieldName.charAt(1))) {
      throw new IllegalArgumentException("must be upper case");
    }
    return fieldName;
  }

}

For more information see the Java documentation

indexOf

charAt

Charlie Gallentine
Charlie Gallentine
934 Points

Thank you! That makes perfect sense!

You're really close, I just did this one today, and it took me a bit. indexOf(x) returns the index of x in the string. You'll want to use charAt(x) in order to get the character.