2017-04-05 78 views
-4

这是一个练习,我被要求编写方法charAt()length()startsWith()并在main函数中调用这些方法。简单的方法调用在java中不起作用

预期的输出应该

ABCDE

的C 5

出于某种原因,我不知道,所以它不会打印出那些出去放和我无法请致电startsWith()方法。

问题(1)我不能调用方法startsWith()

问题(2)编译时我注释掉startsWith()但比

它只能打印的信不是索引和长度。

public interface CSequence { 
    char charAt(int n); 
    int length(); 
} 
class ImmutableCSequence implements CSequence { 
    private char[] chars; 
    public ImmutableCSequence(char[] chars) { 
     this.chars = new char[chars.length]; 
     for (int pos = 0; pos < chars.length; pos++) 
      this.chars[pos] = chars[pos]; 
    } 
    public boolean startsWith(char c) { 
     boolean b = false; 
     if (this.chars.length > 0 && c == this.chars[0]) 
      b = true; 
     return b; 
    } 
    public String toString() { 
     return new String(this.chars); 
    } 

    public char charAt(int n) { 
     for(int i = 0; i < chars.length; i++){ 
      i=(char) n; 
     } 
     return (char)n; 
    } 

    public int length() { 
     return this.chars.length; 
    } 
    public static void main(String[] args) { 
     char[] letters = {'a', 'b', 'c', 'd', 'e'}; 
     CSequence cs = new ImmutableCSequence(letters); 
     System.out.println(cs); 
     char c = cs.charAt(2); 
     int len = cs.length(); 
     System.out.println(c + " " + len); 
     //boolean b = cs.startsWith('a'); 
    } 
} 
+0

拿什么'没有作用,因为它是supposed'? – Jens

+0

它的开头有可能是拼写错误? –

+0

startWith!= startsWith – luk2302

回答

1

参考csCSequence类型的,并且它只能 激活在接口CSequence方法(方法的charAt和长度)。 它不能激活方法startsWith

方法startWith可以通过参考ImmutableCSequence来激活。

public static void main(String[] args) { 
    char[] letters = {'a', 'b', 'c', 'd', 'e'}; 
    CSequence cs = new ImmutableCSequence(letters); 
    ImmutableCSequence ck = new ImmutableCSequence(letters); 
    System.out.println(cs); 
    char c = cs.charAt(2); 
    int len = cs.length(); 
    System.out.println(c + " " + len); 
    boolean b = ck.startsWith('a'); 

您可以简化您的charAt()这样

public char charAt(int n){ 
return this.chars[n]; 

}