Search code examples
javacharcharat

charAt cannot be dereferenced


Attempting the FizzBuzz problem, however I encounter the issue "charAt cannot be dereferenced". Here is my code below for reference.

  public String fizzString(String str) {

  if ((str.charAt(0).equals('f'))&&(str.charAt((str.length)-1).equals('b'))){
   return "FizzBuzz";
  }
  else if (str.charAt(0).equals('f')){
   return "Fizz";
  }
  else if (str.charAt((str.length)-1).equals('b')){
   return "Buzz";
  }
  else{
   return "FizzBuzz";
  }

}

Solution

  • Let's look following example:

    String str = "fab";
    System.out.println(str.charAt(0) == 'f'); //true
    System.out.println(str.charAt(0).equals('f')); //error: Cannot invoke equals(char) on the primitive type char
    System.out.println(Character.toString(str.charAt(0)).equals("f")); //true
    System.out.println(str.startsWith("f")); //true
    

    How about if the str is a empty string:

    String str = "";
    System.out.println(str.charAt(0) == 'f'); //java.lang.StringIndexOutOfBoundsException
    System.out.println(str.charAt(0).equals('f')); //error: Cannot invoke equals(char) on the primitive type char
    System.out.println(Character.toString(str.charAt(0)).equals("f")); //java.lang.StringIndexOutOfBoundsException
    System.out.println(str.startsWith("f")); //false
    

    Now I think you have already known to use String.startsWith and String.endsWith are better than String.charAt.