2013-07-11 154 views
-1

我一直在試圖執行這個程序,許多人會覺得有點無用。不過,我一直在收到這個錯誤:在執行時,線程「main」java.lang.StringIndexOutOfBoundsException異常。這個程序是要找到元音,輔音,特殊字符等的數量,我最近得到了這個錯誤。請幫助我。什麼是這個錯誤,我如何從我的代碼中刪除它。提前感謝。錯誤:線程「主」中的異常java.lang.StringIndexOutOfBoundsException

import java.io.*; 
public class numberof { 
public static void main(String args[])throws IOException{ 
BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); 
System.out.println("Enter string"); 
String str=br.readLine(); 
int vowel=0,consonant=0,upcase=0,locase=0,special=0,dig=0; 
int l=str.length(); 
for(int in=1;in<=l;in++){   //This also is being displayed as an error 
    char c=str.charAt(in);   //This is the error Line. 
    if(c>=65||c<=90||c>=97||c<=123){ 
     if(c=='a'||c=='A'||c=='e'||c=='E'||c=='o'||c=='O'|c=='u'||c=='U'){ 
      vowel++; 
      if(c>=65 && c<=90){ 
       upcase++; 
       } 
      else{ 
       locase++; 
       } 
     } 
     else{ 
      consonant++; 
      if(c>=65 && c<=90){ 
       upcase++; 
      } 
      else{ 
       locase++; 

        } 
       } 

      } 
    else if(c>=48 && c<=57){ 
     dig++; 
     } 
    else{ 
     special++; 
    } 

    } 
    System.out.println(upcase+" "+locase+" "+vowel+" "+consonant+" "+dig+" "+special); 
} 
    } 

回答

2
for(int in=1;in<=l;in++) 

應該

for(int in=0;in<l;in++) 

數組索引從零開始(in =0假設你從第一個元素想)

編輯:

lString[]長度,讓我們說5分成a[0], a[1], a[2], a[3], a[4]。如果你觀察,現在你可以從0(或)1(或)2開始,但是最多隻能使用a[4],當你使用in <=時,循環會檢查直到引發indexoutofBounds異常的[5]。

+0

它的工作。金錢!!!!和抱歉問(從我身邊有點愚蠢)。 – Abhinav

+0

@ user2511145:以小例子更新答案,祝你好運! – kosa

+0

Thanks.Appreciate this。 – Abhinav

0

在你的for循環中,你從索引1開始,在小於或等於時循環。

for (int in = 1; in <= l; in++) {} 

這意味着你會循環2比你應該。所以它應該是:

for (int in = 0; in < l; in++) {} 

數組索引是從零開始的,所以它從0循環到長度而不是從1到長度。

寫這個的另一種方法是這樣的:

for(int i = 0; i < str.length(); i++) {} 

大多數Java開發人員會發現這更容易閱讀。

0

是否要搜索所有字符串中的元音,從第一個字符開始?使用for(int in=0; in<l; in++)

相關問題