gpt4 book ai didi

java - 查找一个数字是否在数组中,如果是,则出现了多少次

转载 作者:行者123 更新时间:2023-12-02 09:51:56 24 4
gpt4 key购买 nike

问题是有一个 10000 的数组已经为我填满了。填充数组的数字范围将在 0 到 2500 之间。该数组未排序。我的目标是通过一次线性搜索找到 1320 的存在,第二次线性搜索将检查数字 1320 出现了多少次。该数组是一个随机数组。

我尝试设置线性搜索来检查数组中的数字是否存在。我还尝试设置线性搜索来检查数组存在的次数。两者都不起作用,这是我第一次使用数组,所以我不确定我是否正确地执行了它们

public static void main(String[] args) {
// Finish adding Code
boolean DoesItExist;
int iHowMany;
final int SIZE = 10000, ENTRY = 1320;
int[] NumArray = new int[SIZE];


OwenHeading.getHeader("Assignment 9: Arrays.");
fillTheArray(NumArray, SIZE);
System.out.println("DONE");
}


public static void fillTheArray(int[] iTempArray, int SIZE) {
final int RANGE = 2500;
Random rand = new Random();

for (int index = 0; index <= SIZE - 1; index++)
iTempArray[index] = rand.nextInt(RANGE);
}

public static boolean linearSearchOne(int[] iTempArray, int SIZE, int ENTRY) {

boolean TempDoesItExist;

return TempDoesItExist;
}

public static int linearSearchTwo(int[] iTempArray, int SIZE, int ENTRY) {

int HowManyExist;

return HowManyExist;
}

public static void programOutput(boolean TempDoesItExist, int TempHowMany) {

if (TempDoesItExist)
System.out.println("does");
// Cool, you found the number 1320
else
System.out.println("does not");
// Dang, you didn't find the number 1320
}

}

我并不是要求确切的答案,只是寻求一些帮助,让我朝着正确的方向前进。我觉得如果我从头开始,我可以更轻松地完成这个项目,但我的老师希望我们使用他的入门项目。

最佳答案

初始化你的 boolean 值和计数器

Bool doesItExist = false;
Int iHowManyTimes = 0;

您可以像这样以线性方式检查 java 数组中的值:

for (int number : NumArray) {
if (anItemInArray == myValue) {
doesItExist = true;
return;
}
}

然后再重复一遍并增加计数器

    for (int number : NumArray) {
if (number == ENTRY) {
iHowMany += 1;
}
}

编辑:将 Return 语句添加到第一个循环,因为找到值后没有理由继续

关于java - 查找一个数字是否在数组中,如果是,则出现了多少次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56261480/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com