Twitter allows users to send messages of 140 characters or less. Users direct tw
ID: 3769410 • Letter: T
Question
Twitter allows users to send messages of 140 characters or less. Users direct tweets to specific users by using @mentions and label tweets by using #hashtags. Tweets may also contain links that start with http://.
For this lab you will ask the user to enter a potential tweet. First you will check to see if it is a valid tweet by checking that the length is less than or equal to 140 characters.
If the tweet is too long print out the number of characters over 140.
If the tweet is valid print Length Correct and count the number of @mentions, #hashtags and number of links using the following rules:
Every mention will start with the '@' character and have at least one non-space or non-tab character following it.
All hashtags will start with the '#' character and have at least one non-space or non-tab character following it.
All links will start with the string "http://". Twitter ignores case, so HTTP and http are counted as the same set of characters. You do not need to check for any characters following the http:// .
Remember that the escape sequence, ' ', can be used to check for a tab character.
Sample Run 1:
Please enter a tweet:
This is a #long tweet. An extra long #link. So, when @you write your code it should ignore all of the #hastags and @mentions since it is too long. It should also ignore all http://links
Excess Characters: 45
Sample Run 2:
Please enter a tweet:
This #tweet is #short and has several #hashtags. And HTtp://links @and @mentions
Length Correct
Number of Hashtags: 3
Number of Attributions: 2
Number of Links: 1
Explanation / Answer
import java.util.Scanner;
public class Twitter {
public static void main(String[] args)
{
Scanner s=new Scanner(System.in);
String input="";
int hashtags=0,Attributions=0,Links=0;
System.out.println("Please enter you tweet");
input=s.nextLine();
if(input.length()>140)
{
System.out.println("number of characters over 140.");
System.out.println("Excess Characters. "+(input.length()-140));
System.exit(0);
}
if(input.length()<=140){
System.out.println("Length Correct.");
String array[]=input.split(" ");
for(int i=0;i<array.length;i++)
{
if(array[i].charAt(0)=='@' && (array[i].charAt(1)!=' '||array[i].charAt(1)!=' '))
{
Attributions++;
}
if(array[i].charAt(0)=='#' && (array[i].charAt(1)!=' '||array[i].charAt(1)!=' '))
{
hashtags++;
}
if(array[i].toLowerCase().indexOf("http://")==0 ||array[i].toLowerCase().indexOf("HTTP://")==0 )
{
Links++;
}
}
}
System.out.println("Number of Hashtags: "+hashtags);
System.out.println("Number of Attributions: "+Attributions);
System.out.println("Number of Links: "+Links);
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.