Java 当count等于零时,如何不返回任何内容?

Java 当count等于零时,如何不返回任何内容?,java,Java,如果count大于零,我希望函数countChar只返回一个值,否则我希望它什么也不返回 我知道该方法不能返回null,因为null不能是Int。有没有其他方法可以有效地返回“null”值 publicstaticintcountchar(stringstr,charch){ 整数计数=0; 对于(int i=0;i0){ 返回计数; }否则{ 返回null; } } 错误:不兼容的类型:无法转换为int 返回null; ^ 我希望它返回绝对零而不是零。使用Integer而不是int,其他一切

如果count大于零,我希望函数countChar只返回一个值,否则我希望它什么也不返回

我知道该方法不能返回null,因为null不能是Int。有没有其他方法可以有效地返回“null”值

publicstaticintcountchar(stringstr,charch){
整数计数=0;
对于(int i=0;i0){
返回计数;
}否则{
返回null;
}
}
错误:不兼容的类型:无法转换为int 返回null; ^
我希望它返回绝对零而不是零。

使用
Integer
而不是
int
,其他一切保持不变:

public static Integer countChar(String str, char ch){...} 

但是方法命名没有意义——countChars统计字符串中出现字符的次数。如果一个特定的字符没有出现,那么0是一个完全合理的响应。Null实际上不是一个合理的响应-如果您想要Null,那么让调用countChars的方法返回0,并像Null一样继续:

int result = countChars("Hello world", 'z');
if(result == 0)
  someMethod(null);
else
  someMethod(result.ToString());

即使抛出异常也比返回null要好,因为它至少会告诉开发人员谁在使用您的代码,什么是错误的,并提供一些关于如何修复它的线索。要求代码做一些不应该返回空白响应的事情,而得到一个空白响应可能会让人非常沮丧,你可以通过两种方式来改变它

  • 通过改变给定的比较逻辑。如果它为零,则不会返回任何内容

  • 我认为这不是一个好主意,但如果使用
    Integer
    返回类型,则应该能够返回null。请注意
    int
    (基本类型)与
    Integer
    类类型不同。
    int
    不能接受
    null
    作为值(这就是为什么会出现错误),因此如果将返回类型更改为
    Integer
    ,您将能够在旁注中返回
    null
    ,您将需要检查
    循环,因为当前代码将退出(返回)该方法在第一次迭代之后执行,并且从不重复第二次。如前所述,
    Integer
    就是答案。好奇,这里返回0有什么不对?这计算字符串中的字符数,0是有效值。
    int result = countChars("Hello world", 'z');
    if(result == 0)
      someMethod(null);
    else
      someMethod(result.ToString());
    
    if (count > 0) {
        return count;
      }
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    OR
    
    2. You can return null but change the return type of method from primitive to nonprimitive.
    
    ~~~~~~~~~~~~~~~~~~~~
    public static Integer countChar(String str, char ch){
    
    ---
    ---
    if (count>0) {
        return count;
      }
    
        return null; 
    } 
    ~~~~~~~~~~~~~~~~~~~