【问题标题】:Occurrences of a number in a string字符串中数字的出现次数
【发布时间】:2013-10-10 20:43:40
【问题描述】:

我需要找出数字 1 在诸如“11100011”之类的字符串中出现的次数 这样我就可以使用计数来做一些奇偶校验位工作。我想知道是否有人可以告诉我什么方法或如何设置循环来做这样的事情。

public class message
{
    private String parity1;
    private int count;

    public message(String Parity1)
    {
        parity1 = Parity1;
        int count = 0;
    }

    public static int countOnes(String parity1, char 1)
    {
        count = 0; 
        for(int i = 0; i < parity1.length(); i++) {
            if(parity1.charAt(i)==1){
                count++;
            }
        }
        return count;
    }
//...

【问题讨论】:

  • blah blah blah 你试过什么 blah blah blah(IOW,阅读常见问题解答)
  • 使用for循环并在字符串上调用charAt
  • 让我们看看你目前拥有什么。
  • 字符串 ar = "111000011"; int countOfOnes = ar.length() - ar.replaceAll("1", "").length();
  • 这就是我得到的 char 1 的标识符预期错误

标签: java loops


【解决方案1】:

你的比较有问题:

if(parity1.charAt(i)=='1'){//note the quotes; needed to interpret '1' as a char
  count++;
}

注意这个函数签名是错误的:

public static int countOnes(String parity1, char 1)

应该是:

public static int countOnes(String parity1)

那里不需要第二个参数。如果您想传入此参数,请使用:

public static int countOnes(String haystack, char needle)

然后你的比较变成:

if(haystack.charAt(i)==needle){

还要注意,此方法中声明的count 是错误的。您正在尝试从静态函数中引用对象的成员字段。静态函数不与对象相关联,而是与类相关联。鉴于您不需要任何成员字段,您不妨在 countOnes 函数中声明 count

public static int countOnes(String parity1) {
  int count = 0;
  //...
}

【讨论】:

    猜你喜欢
    • 2010-10-20
    • 2014-04-24
    • 1970-01-01
    • 2012-05-10
    • 2020-05-06
    • 2020-02-21
    相关资源
    最近更新 更多