2017-02-08 67 views
0

这是一个针对学校的项目。其目标是创建一个读取用户输入的程序,然后通过随机删除字符来缩短输入,直到达到140个字符。这是我迄今为止所做的。目前,它只删除一个字符,然后停止运行。感谢您的任何建议从字符串中删除随机字符

import java.util.Scanner; 
import java.util.Random; 

public class Main { 

public static void main(String[] args) { 

     Scanner keyboard = new Scanner(System.in); 
     System.out.println("Enter the tweet you want to shorten:"); 
     String tweet = null; 

     tweet = keyboard.nextLine(); 

     int tweetLength = tweet.length(); 

     Random rand = new Random(); 


     do { 

     } while (tweetLength <= 140); { 
      int characterposition = rand.nextInt(tweetLength); 
      String shorttweet = tweet.substring(0, characterposition-1); 
      String shorttweet2 = tweet.substring(characterposition); 

      tweet = shorttweet + shorttweet2; 
      System.out.println("Shortented Tweet: " + tweet); 
      tweetLength = tweet.length(); 

     } 
+1

哇,这是一个令人印象深刻环... – shmosel

回答

1

您的循环的格式是错误的。您应该使用:

public static void main(String[] args) { 

    Scanner keyboard = new Scanner(System.in); 
    System.out.println("Enter the tweet you want to shorten:"); 
    String tweet = null; 

    tweet = keyboard.nextLine(); 

    int tweetLength = tweet.length(); 

    Random rand = new Random(); 

    while (tweetLength > 140) { 
     int characterposition = rand.nextInt(tweetLength); 
     String shorttweet = tweet.substring(0, characterposition); 
     String shorttweet2 = tweet.substring(characterposition + 1); 

     tweet = shorttweet + shorttweet2; 
     System.out.println("Shortented Tweet: " + tweet); 
     tweetLength = tweet.length(); 
    } 

你以前有什么是空do-while循环之后的代码一块,这就是为什么它只是发生一次。请注意,我也改变了循环条件 - 我们应该在长度大于140的时候循环,而不是在小于时循环。

为了便于学习,下面是你原来的循环:

do { 
    //you didn't do anything inside the loop! 
} while (tweetLength <= 140); 

//all of your code was after the loop 

编辑:

我们还需要解决这一行rand.nextInt(tweetLength),因为这将返回一个int介于0(含)tweetLength(独家)。当这个返回0时,下一行将会中断,因为你正在调用substring(0, -1)。由于PatrickParker对于这一点

+0

你的位置是关闭的一个。当nextInt返回0时,这可能导致java.lang.StringIndexOutOfBoundsException。 –

+0

@PatrickParker好点,固定的。 – nhouser9

+0

不,你只是不可能删除第一个字符。 –

1

你最好由StringBuilder,这是快得多这种操作的替代String

private static String shorten(String str, int length) { 
    StringBuilder sb = new StringBuilder(str); 
    Random rand = new Random(); 
    while (sb.length() > length) { 
     int pos = rand.nextInt(sb.length()); 
     // The deleteCharAt() method deletes the char at the given 
     // position, so we can directly use the retrieved value 
     // from nextInt() as the argument to deleteCharAt(). 
     sb.deleteCharAt(pos); 
    } 
    return sb.toString(); 
} 

要回答你的问题:

您正在使用具有以下格式的do-while循环:

do { 
    // Things to do 
} while (condition); 

您在这段代码后面的块与此循环无关。这只是一个匿名代码块

{ 
    // Statements 
} 

所以首先你的空do-while循环执行,然后在它下面的代码 - 一次,当然。

您应该使用while循环,而不是:

while (lengthOfString > 140) { 
    // remove a character 
}