【发布时间】:2014-12-18 00:40:05
【问题描述】:
我有一个程序应该检查字符串中#s 和@s 的数量。我的代码可以正常工作,但是当它到达字符串中的一个空格时,for 循环会中断,而没有明显的原因。我在网上进行了广泛的查找,但在文档或其他帮助论坛中找不到关于此类问题的任何内容。 问题不是代码给出错误,它只是退出循环。
for(int i = 0; i < length; i++){
if(tweet.charAt(i) == '@' && tweet.charAt(i+1) != ' '){
attribution++;
}
else if(tweet.charAt(i) == '#' && tweet.charAt(i+1) != ' '){
hashtag++;
}
}
下面是一些运行代码的例子:
> run Main
Please enter a tweet:
#hashtag@attribution#hashtag
Length Correct
Number of Hashtags: 2
Number of Attributions: 1
Number of Links: 0
>
> run Main
Please enter a tweet:
#hashtag @attribution #hashtag
Length Correct
Number of Hashtags: 1
Number of Attributions: 0
Number of Links: 0
>
这是整个程序:
import java.io.*;
import static java.lang.System.*;
import java.util.Scanner;
import java.lang.Math;
class Main{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int hashtag = 0;
int attribution = 0;
int link = 0;
System.out.println("Please enter a tweet:");
String tweet = scan.next();
int length = tweet.length();
if(length > 140){
int excess = length - 140;
System.out.println("Excess Characters: " + excess);
}
else if(length-1 <= 140){
for(int i = 0; i < length; i++){
if(tweet.charAt(i) == '@' && tweet.charAt(i+1) != ' '){
attribution++;
}
else if(tweet.charAt(i) == '#' && tweet.charAt(i+1) != ' '){
hashtag++;
}
}
System.out.println("Length Correct\nNumber of Hashtags: " + hashtag + "\nNumber of Attributions: " + attribution + "\nNumber of Links: " + link);
}
else{
System.out.println("What the bloody hell have you done?");
}
}
}
【问题讨论】:
-
length是如何计算的? -
打印字符串并向我们展示它的内容 System.out.println("-" + tweet + "-");
-
应该是; i ,因为 .charAt(i+1) 超出边界。
-
@user2336634 不,它没有。
-
对不起,我不相信你。也许您运行的代码版本与您描述的版本不同,或者问题可能与您所说的不同,但是在检查
length字符之前,该循环不会以任何方式退出,除非tweet是null或者其中的字符数少于length。
标签: java string for-loop char break