我正在尝试在不同的位置检查字符串是否为连字符(对于电话号码,因为输入不同),但我一直收到错误
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);
答案 0 :(得分:18)
如果你使用这样的东西,它会起作用:
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
而不是String
。 equals()
方法只能用于对象。 Char是primitive data type,没有方法。对于字符,您应该使用==
或!=
等操作符。