2013-11-03 1 views
0

저는 자바를 처음 사용하고 트윗의 #s를 계산하는 과제가 있습니다 (#는 단어의 시작 부분에 있어야합니다).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); 
    } 
}