当charAt(i)=''时,如何防止Java for循环中断?

时间:2014-10-22 14:14:38

标签: java string for-loop char break

我有一个程序,它应该检查一个字符串中#s和@s的数量。我的代码工作正常,但是当for循环到达字符串中的空格时,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?");
    }
  }
}

4 个答案:

答案 0 :(得分:3)

@#字符位于字符串末尾时,您的代码将会中断,因为您检查charAt(i+1)时未确保i+1小于{{{} 1}}。

有一种更简单的方法可以找出字符串中的哈希标记和length的数量 - 您需要做的就是用空字符串替换所需的字符,并比较长度,如下所示:< / p>

@

注意正则表达式的String text = "..."; int numHashTags = text.length() - text.replaceAll("#(?!\\s)", "").length(); int numAttr = text.length() - text.replaceAll("@(?!\\s)", "").length(); 。这些negative lookaheads阻止正则表达式在符号后面跟一个空格匹配。

答案 1 :(得分:0)

您的代码没有进行边界检查 当您访问i + 1元素且i等于length - 1时,您将通过无效索引(length)进行访问,从而导致错误。
(我假设length是字符串的长度)

此外,此任务可以使用正则表达式在一行代码中完成!尝试这样做而不是写循环。 (除非您已经知道这是性能瓶颈,并且您正在尝试优化)

答案 2 :(得分:0)

 for(int i = 0; i < tweet.length() - 1 ; i ++){
   if (tweet.charAt(i+1) != ' '){
    if(tweet.charAt(i) == '@'{
        attribution++;
   }
   else if(tweet.charAt(i) == '#' ){
      hashtag++;
  }
 }
}

答案 3 :(得分:-1)

我在http://www.compileonline.com/compile_java_online.php尝试了您的代码,并以此示例结束。

public class HelloWorld{

 public static void main(String []args){
    String test = "Hello #Wor@l@d";
    int hasHashTag = 0;
    int hasAt = 0;
    for (int i = 0; i < test.length(); i++) {
        if (test.charAt(i) == '#') hasHashTag++;
        if (test.charAt(i) == '@') hasAt++;
    }
    System.out.println(hasHashTag);
    System.out.println(hasAt);
 }

}