gpt4 book ai didi

java - 在Java中查找数组中的多个搜索结果

转载 作者:太空宇宙 更新时间:2023-11-04 08:49:56 24 4
gpt4 key购买 nike

我制作了一个由名字组成的数组。我有一个搜索函数,可以搜索数组的元素,并且工作正常。但是,对于数组的多个元素,我不知道如何打印返回了多少个结果。例如,如果在我的示例中找到“John”(确实如此),我不知道如何表明找到了多个结果。请有人帮助我。我需要让“计数”为找到的每个结果增加 1 倍。这是我的代码:`

import java.util.*;

class Search {
public static void main(String[] args) {

Scanner search = new Scanner(System.in);
String[] firstName = new String[]{"John", "Thomas", "Samuel", "Chris", "Daniel", "Joey", "David", "Joshua", "Michael", "John"};
Arrays.sort(firstName);
System.out.print("Enter a search term: ");
String name = search.next();

int i;

boolean foundIt = false;

search:
for (i = 0; i < firstName.length; i++) {
if (firstName[i] == name) {
foundIt = true;

}
}


if (foundIt = true){
System.out.println("Your search term of " + name + " produced " + count + " search results");
}

else {
System.out.println("Your search term of " + name + " did not return any results");
}
}
}

最佳答案

您可以将 boolean 型foundIt更改为int count,并在将foundIt设置为true的位置递增。

所以类似:

int count = 0;

search:
for (i = 0; i < firstName.length; i++) {
if (firstName[i] == name) {
count++;
}
}


if (count > 0){
System.out.println("Your search term of " + name + " produced " + count + " search results");
}

else {
System.out.println("Your search term of " + name + " did not return any results");
}

关于java - 在Java中查找数组中的多个搜索结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3578954/

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