【发布时间】:2014-07-28 09:49:58
【问题描述】:
我编写了方法 'charCount()' 来返回字符串 'chc',但是 netbean 迫使我返回 null。 'return null' 是否也禁止我在此方法之外使用 'chc',或者它被很好地返回。刚接触java我很困惑。
// static String chc ;
public static String charCount(String [] a){
String chc ;
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[i].length(); j++) {
char ch = a[i].charAt(j);
int charcout = a[i].length();
chc= Character.toString(ch)+""+Integer.toString(charcout)+" ";
// String chc= ch + "" + charcout + " ";
return chc;
//System.out.print(chc);
}
}
return null; //NETBEAN IS FORCING ME TO WRITE THIS TO AVOID COMPILE TIME ERROR
}
我需要帮助来纠正此代码以避免返回 null。
【问题讨论】:
-
chc 在范围之外不可用。你可以在 for 循环之前声明 chc。
-
如果您的目标是返回一个字符串,描述数组中每个字符串中每个字符的频率,则此方法的逻辑将无法实现。一旦你修复了逻辑,在方法末尾有
return null的要求可能会变得无关紧要。 (在循环中间调用return意味着两个循环永远不会执行超过一次。)