2013-11-04 46 views
-2

我是java新手,我有一個任務來計算#s,@s和tweets中的鏈接。所以我編寫了這個程序,編譯器沒有看到任何錯誤,但是當我運行它並輸入推文時,它會給我帶來錯誤。爲什麼我的代碼在運行時不斷給我提供錯誤?它編譯得很好

public static void main (String str[]) throws IOException { 
     Scanner scan = new Scanner(System.in); 

     System.out.println("Please enter a tweet."); 
     String tweet=scan.nextLine(); 
     int quantity = tweet.length(); 
     System.out.println(tweet); 
     if (quantity > 140) 
     { 
     System.out.println("Excess Characters: " + (quantity - 140)); 
     } 
     else{ 
     System.out.println("Length Correct"); 
     int hashtags=0; 
     int v=0; 
     if (tweet.charAt(0)=='#'){ 
     hashtags++; 
     v++; 
     } 
     String teet=tweet; 
      while (hashtags != v-1){ 
      v++; 
      int hashnum= teet.indexOf('#'); 
      if ((teet.indexOf('#')!=-1) && (teet.charAt(hashnum + 1)!=(' ')) && (teet.charAt(hashnum-1)==(' '))) { 
      hashtags++; 
      } 
      if (teet.indexOf('#')!=-1) { 
      teet=teet.substring((hashnum+1),(quantity)); 
       } 
      } 
     System.out.println("Number of Hashtags: " + hashtags); 
     int ats=0; 
     int w=0; 
     if (tweet.charAt(0)=='@'){ 
      ats++; 
      w++; 
     } 
     String tweat=tweet; 
     while (ats != w-1){ 
      w++; 
      int atnum= tweat.indexOf('@'); 
      if ((tweat.indexOf('@')!=-1) && (tweat.charAt(atnum + 1) !=(' ')) && (tweat.charAt(atnum-1)==(' '))) { 
      ats++; 
      } 
      if (tweat.indexOf('@')!=-1) { 
      tweat=tweat.substring((atnum+1),(quantity)); 
      } 
     } 
     System.out.println("Number of Attributions: " + ats); 

} 
} 
} 

感謝任何能幫助的人。

+6

它會給你錯誤吧?哪些錯誤? –

+1

是否給出了關於錯誤在哪裏或什麼的任何行或痕跡? 此外,您的格式很難閱讀。 –

+0

當我鍵入#hi,它會這樣說: –

回答

0

String.indexOf(String)方法將爲第一個字符返回0。 異常被拋出時:

teet.charAt(hashnum - 1) 

因爲hashnum是0,你在做什麼是 「#hi」 .charAt(-1)。

相關問題