charAt()。equals()导致“char无法解除引用” [英] charAt().equals() causes "char cannot be dereferenced"
本文介绍了charAt()。equals()导致“char无法解除引用”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试在不同的位置检查字符串是否为连字符(因为输入的内容因电话号码而异),但我一直收到错误
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无法解除引用
char cannot be dereferenced
代码:
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 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");
}
问题在于 raw。 charAt(n)
返回 char
而不是 String
。 equals()
方法只能用于对象。 Char是原始数据类型,没有任何方法。在字符上你应该使用像 ==
或!=
这样的运算符。
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 !=
.
这篇关于charAt()。equals()导致“char无法解除引用”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文