【问题标题】:How do I keep Java for loops from breaking when charAt(i) = ' '?当 charAt(i) = ' ' 时,如何防止 Java for 循环中断?
【发布时间】: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 字符之前,该循环不会以任何方式退出,除非 tweetnull或者其中的字符数少于length

标签: java string for-loop char break


【解决方案1】:

@# 字符位于字符串末尾时,您的代码将中断,因为您检查charAt(i+1) 时没有确保i+1 小于length

有一种更简单的方法可以找出字符串中的哈希标签和@s 的数量 - 您需要做的就是用空字符串替换所需的字符,然后比较长度,如下所示:

String text = "...";
int numHashTags = text.length() - text.replaceAll("#(?!\\s)", "").length();
int numAttr = text.length() - text.replaceAll("@(?!\\s)", "").length();

注意正则表达式的(?!\\s)。这些negative lookaheads 可防止正则表达式在符号后跟空格时匹配该符号。

【讨论】:

  • 我尝试使用你的正则表达式,但它们仍然和我的代码有同样的问题;他们不会在空格后计算#s 或@s。我开始怀疑我使用的编译器是否有问题。
  • @user2336634 我无法确定,但这肯定适用于 ideone (demo)。
【解决方案2】:

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

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

【讨论】:

  • 虽然这是真的,但它并不能回答问题。 OP 说他的循环“中断”(过早退出),并且它在到达 space 时执行它。
【解决方案3】:
 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++;
  }
 }
}

【讨论】:

  • 虽然此代码确实解决了越界索引问题,但它没有回答问题(请参阅 cmets 中的说明)。不过,公平地说,所澄清的问题是不一致的。
【解决方案4】:

我在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);
 }

}

【讨论】:

  • 这是一个怎样的答案?您没有帮助 OP 让他的代码正常工作,而是从中删除了功能(显然他不想计算后跟空格字符的 # 和 @,而您进行了该测试)。
  • 实际上,您好,第一句话指出“我有一个程序应该检查字符串中#s 和@s 的数量”。它后面的空格没有任何限制,除了它存在于他的代码中之外,还不清楚它应该以这种方式编码。应该以这种方式完成并不是“显而易见的”。
  • 公平点,但由于这似乎与 Twitter 字符串有关,' ' 测试似乎更有可能是故意的,他只是没有清楚地说明他的问题。
猜你喜欢
  • 1970-01-01
  • 2017-11-15
  • 2013-04-26
  • 2010-12-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-10
  • 1970-01-01
相关资源
最近更新 更多