0

私は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);
            }
     }
}

コンパイラはエラーを検出しませんが、実行すると print 以外はすべて実行されます("Number of Hashtags: " + hashtags)。誰か助けてくれませんか?ありがとうございました。

4

1 に答える 1

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);
    }
}
于 2013-11-03T20:14:34.697 に答える