亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何計算一個字母在數組的所有字符串中出現的次數?

如何計算一個字母在數組的所有字符串中出現的次數?

慕蓋茨4494581 2021-11-11 13:42:21
public static int countLetter(String[] x, String y){    int count = 0;    for(int i = 0; i < x.length; i++){        for(int h = 0; h < x[i].length(); h++){            String yo = new String(x[i].substring(h,h+1));            if(yo==y){                count++;}            }        }        return count;    }}我的方法應該返回一個整數,該整數計算字母在數組的所有字符串中出現的總次數。(假設字符串是一個字母,我不能使用 charAt())。
查看完整描述

2 回答

?
慕斯709654

TA貢獻1840條經驗 獲得超5個贊

您可以在第 6 行更改代碼

if(yo==y)

if(yo.equals(y))


查看完整回答
反對 回復 2021-11-11
?
森林海

TA貢獻2011條經驗 獲得超2個贊

問題在于字符串比較。您需要使用equals()或者可能equalsIgnoreCase()在比較 Java 中的 2 個字符串時:


public static int countLetter(String[] x, String y) {

   int count = 0;

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

      for (int h = 0; h < x[i].length(); h++) {

         String yo = new String(x[i].substring(h, h + 1));

         if (yo.equals(y)) {

            count++;

         }

      }

   }

   return count;

}

你也可以用一個char代替String:


public static int countLetter(String[] x, char y) {

   int count = 0;

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

      for (int h = 0; h < x[i].length(); h++) {

         if (x[i].charAt(h) == y) {

            count++;

         }

      }

   }

   return count;

}


查看完整回答
反對 回復 2021-11-11
  • 2 回答
  • 0 關注
  • 240 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號