数组Java返回(值)错误
我在代码中尝试了不同的东西,但总是出错
该程序的说明是,我需要有一个函数(除了来自main之外),它接收整数值数组的参数,还有一个参数告诉用户希望在数组中查找的值
它还必须返回愿望值在数组中重复的次数
这些错误与计数器有关,也有一些与主功能有关
我想我没有正确返回计数器值
这是我目前的代码:
import java.util.Scanner;
import java.util.Arrays;
public class ArregloBusqueda2
{
static int findRepetition(int listOfValues[], int targetValue, int counter)
{
int i;
boolean found = false;
for(i=0; i<listOfValues.length; i++)
{
while((counter < listOfValues.length))
{
if(listOfValues[i] == targetValue)
{
counter = counter + 1;
}
}
}
return counter;
}
public static int main(String[] args)
{
Scanner input = new Scanner (System.in);
int targetValue;
int listOfValues[] = {1,6,3,8,5,8,3,4,8,3};
System.out.println("Please enter the desire number to look for: ");
targetValue=input.nextInt();
findRepetition(targetValue, counter);
if(counter != 0)
{
System.out.println("The frequency of the number " + targetValue + " is: " + counter);
}
else
{
System.out.println ("The number " + targetValue + " is not contained in the array list");
}
}
}
# 1 楼答案
代码中存在多个问题
public static int main(String[] args)
应该是public static void main(String[] args)
findRepetition
有三个参数, 但你经过了两片土地counter
变量未声明逻辑缺陷,如果计数器值小于listOfValues,
while((counter < listOfValues.length))
将继续执行# 2 楼答案
您没有使用必需的参数调用FindRequest(),FindRequest方法接受3个参数,但只传递2个参数
# 3 楼答案
你让你的方法接受三个参数
扪心自问——你是想“通过柜台”,还是只是
return
它?说明书上说是后者调用此方法时,您没有提供正确的输入
那}在{}上{},对吗?因此,在方法调用中提供正确的参数
listOfValues
呢?你想为{同样,您可能不需要传入
counter
。因为Java is always pass-by-value相反,正如您所写,您希望
return counter
。你在找这个修复代码的其余部分是一个学习练习