charAt().equals() causes “char cannot be dereferenced”

前端 未结 1 1734
猫巷女王i
猫巷女王i 2020-12-10 11:23

I am trying to check a string for hyphens at different positions (for a phone number because the input varies), but I keep getting the error

char can

相关标签:
1条回答
  • 2020-12-10 11:49

    If you use something like this, it will work:

      if (raw.charAt(3) == '-' && raw.charAt(7) == '-') {
    
          System.out.println("2 Hyphens at 3 and 7");
    
      } else if (raw.charAt(3) == '-' && raw.charAt(8) == '-') {
    
          System.out.println("2 Hyphens at 3 and 8");
    
      } else if (raw.charAt(3) == '-' && raw.charAt(9) == '-') {
    
          System.out.println("2 Hyphens at 3 and 9");
    
      }
    

    The problem is that raw.charAt(n) returns a char and not a String. The equals() method can be used only on objects. Char is a primitive data type which has no methods. On chars you should use operators like == or !=.

    0 讨论(0)
提交回复
热议问题