2013-11-03 63 views
0

我是新來的java,我有一個任務來計算推文中的#(#必須在單詞的開頭)。下面的代碼:java怎麼不打印最後一行?

 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; 
      String teet=tweet; 
       while ((teet.indexOf('#')!=-1) || v==0){ 
       v++; 
       int hashnum= teet.indexOf('#'); 
       if ((teet.charAt(hashnum + 1)!=(' ')) && (teet.indexOf('#')!=-1)) { 
       hashtags++;} 
       teet=teet.substring(hashnum,(quantity-1)); 
        } 
      System.out.println("Number of Hashtags: " + hashtags); 
      } 
    } 
} 

編譯器沒有檢測到任何錯誤,但是當我運行它,它做的一切,除了打印("Number of Hashtags: " + hashtags)。有人可以幫忙嗎?謝謝。

回答

0

你的while循環永遠不會退出。

而不是

teet=teet.substring(hashnum,(quantity-1)); 

使用

teet=teet.substring(hashnum+1,(quantity-1)); 

而且可能我謙恭地提出各種改進。

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

    System.out.println("Please enter a tweet."); 
    String tweet = scan.nextLine(); 
    System.out.println(tweet); 

    if (tweet.length() > 140) { 
     System.out.printf("Excess Characters: %d%n", tweet.length() - 140); 
    } else { 
     System.out.println("Length Correct"); 

     int hashtags = tweet.length() - tweet.replaceAll("#(?=[^#\\s])", "").length(); 
     System.out.printf("Number of Hashtags: %d%n", hashtags); 
    } 
}