java怎么不打印最后一行?
问题描述:
我是新来的java,我有一个任务来计算推文中的#(#必须在单词的开头)。下面的代码: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);
}
}
}
编译器没有检测到任何错误,但是当我运行它,它做的一切,除了打印("Number of Hashtags: " + hashtags)
。有人可以帮忙吗?谢谢。
答
你的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);
}
}