2014-09-29 72 views
0

我想,一旦我的異常引發它打破了我的循環(使用斷點功能)&打印我(長數組)計算數組的長度,而無需使用length屬性

class Length{ 
    static void length(String p){ 

    int i=0; 
    try{ 
     while(i<=i){ 
     char ch=p.charAt(i); 
     i++; 
     System.out.println(ch); 
    } 


    } 
    catch(Exception e){ 
    System.out.println(e); 
    } 

} 
    public static void main(String s[]){ 

    String a=new String("jack"); 
    length(a); 
    } 
} 
+0

從你的'try'塊拋出的異常會阻止進一步的迭代長度'而'循環。 – 2014-09-29 04:17:56

回答

3

你可以改變你的代碼如下

static int length(String p) { 
    int i = 0; 
    try { 
     while (i <= i) { 
      char ch = p.charAt(i); 
      i++; 
     } 
    } catch (StringIndexOutOfBoundsException e) { // catch specific exception 
     // exception caught here 
    } 
    return i; // now i is the length 
} 


public static void main(String s[]) { 
    String a = "jack"; 
    System.out.println(length(a)); 
} 

輸出地說:

4 
+0

Thanku有沒有其他方式我可以編碼,並找到長度也如果我不捕捉異常,那麼我怎麼能得到長度 – Jack 2014-09-29 04:13:59

+0

@傑克是有很多方法。您可以通過將字符串拆分爲字母來逐個計算元素。 – 2014-09-29 04:16:25

0
class Length{ 
    static void length(String p){ 

    int i=0; 
    try{ 
     while(i<=i){ 
     char ch=p.charAt(i); 
     i++; 
     System.out.println(ch); 
    } 


    } 
    catch(Exception e){ 
    System.out.println("String length is : + " i) 
    // System.out.println(e); 
    } 

} 
    public static void main(String s[]){ 

    String a=new String("jack"); 
    length(a); 
    } 
} 
0

我認爲你需要返回你計算length(),你可以通過遍歷char(S)從toCharArray()的東西用在String的換每個運營商像

static int length(String p){ 
    if (p == null) return 0; 
    int count = 0; 
    for (char ch : p.toCharArray()) { 
     count++; 
    } 
    return count; 
} 
0

嘗試下面的應用找到一個字

public class Length { 

public static void main(String[] args) { 
    new Length().length("Jack"); 

} 

private void length(String word){ 
    int i = 0; 
    char []arr = word.toCharArray(); 
    for(char c : arr){ 
     i++; 
    } 
    System.out.println("Length of the "+ word+ " is "+ i); 
} 

}