-1

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";
  }

}
BipoN
  • 93
  • 8
  • Compare primitive types like `char` with `==`. – Johannes Kuhn Nov 05 '19 at 05:46
  • It returns a`char`, which you compare with `==`. – user207421 Nov 05 '19 at 05:47
  • Interestingly, this is exactly the type of thing that the infamous FizzBuzz question is meant to reveal. – MarsAtomic Nov 05 '19 at 05:53
  • I instead use the startWith() and endWith() functions instead which helped solve my issue, using this example however with == and changing length to length(), still did not fix my issue for this version. – BipoN Nov 05 '19 at 05:56
  • 2
    *thoughts?* Instead of `String.charAt` I would prefer `String.startsWith` and `String.endsWith`. Instead of performing the tests multiple times, I would save the results to local variables. I would ***start*** with `boolean f = str.startsWith("f"), b = str.endsWith("b");`. Don't forget to return the original `str` if neither condition is true (you currently return "FizzBuzz" twice). If you **really** want to use `String.charAt` - `boolean f = str.charAt(0) == 'f', b = str.charAt(str.length() - 1) == 'b';` – Elliott Frisch Nov 05 '19 at 05:58

1 Answers1

1

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.

LHCHIN
  • 3,679
  • 2
  • 16
  • 34