我是java的新手,我有一个在推文中计算#s的任务(#必须在单词的开头)。这是代码:
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)
之外的所有操作。有人可以帮忙吗?谢谢。
答案 0 :(得分:0)
你的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);
}
}