2017-01-10 17 views
-5

在此作業中,您將撰寫Tweet測試器。 Twitter允許用戶發送140個字符或更少的消息。用戶通過使用@mentions並通過使用#hashtags標記推文來向特定用戶發送推文。用戶也可以「轉推」來自其他用戶的推文。 對於本實驗,您將要求用戶輸入潛在的推文。首先,您將通過檢查長度小於或等於140個字符來檢查它是否是有效的推文。 如果推文太長,則打印超過140個字符的數量。 如果推文有效,請打印長度正確,然後計算@mentions和#hashtags的數量,並根據以下規則確定推文是否爲推特: 每提到一次,將以「@」字符開始,並在其後至少有一個非空格或非製表符。 所有主題標籤都以'#'字符開頭,並且至少有一個非空格或非製表符。 推文是一個轉推,如果它包含字符串「RT:」在推文的文本中的任何地方。 Twitter忽略大小寫,因此「RT:」,「rt:」和其他任何可能的大寫都被計爲相同的字符集,並且都表示轉推。您不需要檢查「RT:」字符串後面的任何字符。 請記住,轉義序列'\ t'可用於檢查製表符。 示例運行1: 請輸入推文: RT:這是一條#long推文。超長的#link。所以,當@you編寫代碼時,它應該忽略所有#hashtags和@mentions,因爲它太長了。它也應該忽略轉推字符串。 過量人物:50 樣品運行2: 請輸入推文: 此#tweet是#short並有幾個#hashtags。 RT:這是一個轉推。 長度正確 提及次數:0 哈希標籤數量:3 輸入是一個轉推。 樣品試驗2: 請輸入鳴叫: 這@tweet是#short並具有和#哈希標籤#@mentions長度 正確 提及數:2 號碼#標籤:2 輸入不是轉推。爲什麼程序拋出這個錯誤??:線程「main」中的異常java.lang.StringIndexOutOfBoundsException:字符串索引超出範圍:36

import java.util.Scanner; 
import java.lang.Math; 

public class Main{ 
    public static void main(String[] args) 
    { 
     Scanner scan = new Scanner (System.in); 
     int h = 0; 
     int m = 0; 
     int count = 0; 
     char letter; 
     boolean r = false; 
     String tweet; 
     System.out.println("Please enter a tweet:"); 
     tweet = scan.nextLine(); 
     int length = tweet.length(); 

     if (length <= 140) 
     { 
      while (count <= length) 
      { 
      letter = tweet.charAt(count); 

      if (letter == '#' && 
       tweet.charAt(letter+1) != ' ') 
      { 
       h++; 
      } 

      if (letter == '@' && 
       tweet.charAt(letter+1) != ' ') 
      { 
       m++; 
      } 

      if ((letter == 'r' || letter == 'R') && 
      (tweet.charAt(letter + 1) == 't' || tweet.charAt(letter + 1) == 'T')) 
      { 
       r = true; 
      } 

      count ++; 

      } 

      System.out.println("Length Correct"); 
      System.out.println("Number of Mentions: " + (m)); 
      System.out.println("Number of Hashtags: " + (h)); 
      if (r == true) 
      { 
      System.out.println("The input was a retweet."); 
      } 
      else if (r==false) 
      { 
      System.out.println("The input was not a retweet."); 
      } 
     } 

     if (length > 140) 
     { 
     System.out.println("Excess Characters: " + (length - 140)); 
     } 


    } 
} 
+0

首先,你將超過與陣列'而(計數<=長度)',從而改變爲'<''其次信+ 1'?也許'count + 1',但是你會在最後超過你的數組 –

+0

這是很多文本的方式,你的代碼示例很難看到實際的問題。請減少輸入,以便於幫助您。 – ppasler

+0

您是否查看了有關此異常的[757個其他問題](http://stackoverflow.com/search?q=StringIndexOutOfBoundsException)? – AxelH

回答

1

以下是問題的原因。

while (count <= length) { 

和下面是修復

while (count < length) { 
相關問題