charAt()。equals()导致“char无法解除引用”

我试图在不同的位置检查字符串的连字符(对于电话号码,因为输入变化),但我一直收到错误

char不能被解除引用

码:

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); 

如果您使用这样的东西,它将起作用:

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

问题是raw.charAt(n)返回一个char而不是Stringequals()方法只能用于对象。 Char是原始数据类型 ,没有方法。 在字符上你应该使用像==!=这样的运算符。