CharAt (). equals () calls "char cannot be dereferenced"

I try to check the string for a hyphen in different positions (for a phone number because the input is changing), but I keep getting an error

char cannot be dereferenced

code:

do { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Enter String"); String raw = br.readLine(); if (raw.length() < 10) { System.out.println(""); System.out.println("Please input a valid phone number of at least 10 digits/letters"); System.out.println(""); } else { if (raw.charAt(3).equals('-') && raw.charAt(7).equals('-')) { System.out.println("2 Hyphens at 3 and 7"); } else if (raw.charAt(3).equals('-') && raw.charAt(8).equals('-')) { System.out.println("2 Hyphens at 3 and 8"); } else if (raw.charAt(3).equals('-') && raw.charAt(9).equals('-')) { System.out.println("2 Hyphens at 3 and 9"); } } } while (1 < 2); 
+6
source share
1 answer

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 , not a String . The equals() method can be used only for objects. Char is a primitive data type that has no methods. In characters you must use operators such as == or != .

+9
source

All Articles