字母计数器(使用子字符串而不是通常的atChar()方法)

时间:2014-06-19 17:04:58

标签: java

我遇到了编程挑战,而且我对如何使其工作有点困惑。 挑战如下:

编写一个程序,要求用户输入一个字符串,然后要求用户输入一个字符。程序应计算并显示指定字符在字符串中出现的次数。

代码:

import java.util.Scanner;
public class F***Around 
{
public static void main(String[] args)
{
    Scanner keyb = new Scanner(System.in);
    String word, character, test;
    int c = 0;

    System.out.println("Enter a word: ");
    word = keyb.nextLine();

    System.out.println("Enter a character: ");
    character = keyb.nextLine();

    for(int x = 1; x <= word.length(); x++)
    {
        test = word.substring(1, 2); 
        if (test.equals(character))
        {
            c += c;
        }
    }

    System.out.println(c);
}
}

它总是在最后返回0,我无法弄清楚出了什么问题。

1 个答案:

答案 0 :(得分:0)

需要进行2次更改:

  1. 使用迭代变量x实际循环遍历字符串。目前,您正在对要比较的子字符串进行硬编码,因此该循环实际上是无用的。
  2. c增加1,因为您每增加1次字符数就会增加计数。
  3. 所以,你的代码应该是这样的:

    for(int x = 0; x < word.length(); x++)
    {
        test = word.substring(x, x+1); 
        if (test.equals(character))
        {
            c += 1;
        }
    }