2014-01-11 18 views
6

我試圖檢查在不同的位置(一個電話號碼,因爲輸入不同)連字符的字符串,但我不斷收到錯誤的charAt()。equals()方法會導致「字符不能被解除引用」

字符不能被解除引用

代碼:

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

'String#charAt()'方法返回什麼? –

+0

'char'是一個原始類型。它沒有辦法。但是你可以用'=='比較字符。 – milleniumbug

+0

爲什麼你不使用正則表達式? –

回答

9

如果使用這樣的事情,它會工作:

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是沒有方法的primitive data type。在字符上,您應該使用像==!=這樣的運營商。

+0

所有對象都有一個'equals()'方法,而不僅僅是'String's。 – Keppil

+0

我正在散步字符串和字符。我會編輯我的答案更加精確。 –