0

I'm new to java and I have an assignment to count #s in tweets (the # has to be at the beginning of the word). Here's the code:

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

The compiler doesn't detect any errors, but when I run it, it does everything except print ("Number of Hashtags: " + hashtags). Can someone please help? Thank you.

Ahmed Ekri
  • 4,601
  • 3
  • 23
  • 42
Matthew Wu
  • 11
  • 1

1 Answers1

0

Your while loop never exits.

Instead of

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

use

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

And might I humbly suggest various improvements.

    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);
    }
}
Paul Draper
  • 78,542
  • 46
  • 206
  • 285