问题是:
Complete the method occursMoreTimes based on the requirements in its comment.
/**
*Returns true if the number of times val1 occurs in the array is strictly greater
*than the number of times val2 occurs in the array. Otherwise, return false.
*If you wish, you can call the findNumberOf method you wrote above.
**/
我的回答是这样的:
public boolean occursMoreTimes(int[] arr, int val1, int val2){
if(findNumberOf(arr, val1) > findNumberOf(arr, val2)){
return true
}
else {return false;
}
}
但是答案键为我在 if 语句中编写的方法调用声明了一个 int ,如下所示:
public boolean occursMoreTimes(int[] arr, int val1, int val2){
int countVal1 = findNumberOf(arr, val1);
int countVal2 = findNumberOf(arr, val2);
if(countVal1 > countVal2){
return true
}
else {return false;
}
}
我的回答可以吗?将方法调用声明为 int 有优势吗?
最佳答案
短语将方法调用声明为 int
并不正确。
该解决方案所做的只是声明一个 int
类型的常规变量来存储方法 findNumberOf()
的返回值。
在您的示例中,为 findNumberOf()
的返回值声明单独的 int 确实没有任何优势。
它可能具有优势的场景是:
您需要在整个函数中多次引用这些值。因此,您可以节省对同一方法的多次调用以及代码空间(名称很可能比对方法的调用短)。
您可以为返回值指定一个特定的名称,从而提高代码的可读性。
这一切都取决于具体情况。对于你的情况来说,这没有什么区别。
关于java - 我是否必须为调用方法的计数器创建整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23420315/