簡體   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