Java charAt().equals() 导致“char 不能被取消引用”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21068134/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 06:21:41  来源:igfitidea点击:

charAt().equals() causes "char cannot be dereferenced"

java

提问by Ds.109

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 cannot be dereferenced

char 不能取消引用

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

采纳答案by N Alex

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 charand not a String. The equals()method can be used only on objects. Char is a primitive data typewhich has no methods. On chars you should use operators like ==or !=.

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