繁体   English   中英

检查输入条目中的每个位置并返回出现字符的次数

[英]Check each position in the input entry and return the number of times a character occurs

我编写了以下代码,但似乎无法将字符串转换为char,然后搜索输入条目字符串。 我的代码如下。 任何有用的提示将不胜感激。 我应该使用while循环,但是感觉起来比较容易。

    public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    String inputEntry;
    String inputCharacter;
    int length;
    int i;
    int counter = 0;

    System.out.println("Enter a string: ");
    inputEntry = in.next();
    System.out.println("Enter a letter: ");
    inputCharacter = in.next();

    length = inputCharacter.length();

    if (length == 1) {
        for(i = 0; i <= inputEntry.length(); i++){
            char c = inputCharacter.charAt(0);
            if (inputEntry.charAt(i) == c){
              counter++;
        }
        }
    }
    else {
        System.out.println("The input letter was not a single letter.");
    }

}

}

看起来代码中的唯一问题是循环中使用的是<=而不是< <=不正确,因为它通过字符串长度作为索引,但是第一个字符位于charAt(0) ,最后一个字符位于charAt(inputEntry.length() - 1)

用以下代码替换循环声明将达到目的:

for(i = 0; i < inputEntry.length(); i++){ 

然后,您还需要System.out.println(counter); 在for循环之后。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM