Advertisement
Guest User

Untitled

a guest
Oct 13th, 2015
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.92 KB | None | 0 0
  1. package tweetshortener;
  2.  
  3. // Imports for user input and random number generator
  4. import java.util.Random;
  5. import java.util.Scanner;
  6.  
  7. /**
  8.  *
  9.  * @author mike
  10.  */
  11. public class TweetShortener {
  12.  
  13.  
  14.     public static void main(String[] args) {
  15.        
  16.         // Setup user input and string variable
  17.         String tweet = new String();
  18.         Scanner userInput = new Scanner(System.in);
  19.        
  20.         // Keep prompting for tweet if string is empty
  21.         while (tweet.isEmpty())
  22.         {
  23.            
  24.             // Prompt for tweet and take user input
  25.             System.out.println("Please enter tweet: ");
  26.             tweet = userInput.nextLine();
  27.  
  28.             // If tweet is under limit, post
  29.             if(tweet.length() <= 140 && !tweet.isEmpty())
  30.             {
  31.                 System.out.println("Tweet posted!");
  32.             }
  33.  
  34.             // If tweet is over the limit, send it to the shortener
  35.             else if (tweet.length() > 140)
  36.             {
  37.                 String shortenedTweet = new String();
  38.                 shortenedTweet = shortenTweet(tweet);
  39.                
  40.                 System.out.println("Tweet shortened and posted: \n" + shortenedTweet);
  41.             }
  42.  
  43.         }
  44.        
  45.     }
  46.    
  47.     // Tweet shortener
  48.     public static String shortenTweet(String tweet)
  49.     {
  50.         // Set up variables
  51.         String shortenedTweet = new String();
  52.         Random generator = new Random();
  53.         int x;
  54.        
  55.         // While tweet is over the limit, remove characters at random
  56.         while(tweet.length() > 140)
  57.         {
  58.             x = generator.nextInt(tweet.length()-1);
  59.            
  60.             // Create a new string around the randomly chosen deletion
  61.             tweet = tweet.substring(0,x) + tweet.substring(x+1);
  62.         }
  63.        
  64.         // Set and return shortened tweet
  65.         shortenedTweet = tweet;
  66.         return shortenedTweet;
  67.     }
  68.    
  69. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement