在字符串数组中搜索字符串[]

时间:2017-08-04 20:05:10

标签: java arrays string search java.util.scanner

我开发了一个控制台应用程序,可以使用循环菜单添加和搜索名称。该应用程序工作正常,除了我搜索名称方法,它返回说找到字符串,从1-49返回到菜单的开头。

Enter name to search: 
rog
Name found at location: 0
...
Name found at location: 49
Enter the number of the menu option you would like to select

我的searchArray方法:

private static void searchArray(String[] nameList, String target) {
    for (int i = 0; i < nameList.length; i++){
        if (nameList[i].equals(target)) {
            System.out.println("Name found at location: " + i);
            }
        else {
            System.out.println("Sorry, name not found");
            }
        }
    }

从我的inputmenuChoice()的这一部分调用void:

else if (menuChoice == 2) {
        System.out.println("Enter name to search: ");

        if (menuScanner.hasNextLine()) {
            String username = menuScanner.nextLine();
            searchArray(nameList,username);
            }
        }

3 个答案:

答案 0 :(得分:0)

<强>解决方案

在我的回答中,我添加了一个布尔值来检查并确保您确实找到了目标的实例,还有一个隐含的变量可以计算您找到目标的次数!希望它适合你!

private static void searchArray(String[] nameList, String target) {
    //Boolean to see if the name was found, int to keep track of how many occurances 
    boolean wasNameFound = false;
    int occ = 0;

    for (int i = 0; i < nameList.length; i++) {
        if (nameList[i].toLowerCase().equals(target.toLowerCase())) {
            System.out.println(target+" Found at index: " + i);
            wasNameFound = true;
            occ += 1;

        } else if (!wasNameFound && (i == nameList.length)){
            System.out.println("Sorry, name not found");
        }
    }

    //Tell user how many occurances of target were found
    if (wasNameFound) {
        System.out.println (target+" Was found " + occ+ " times");
    }
}

答案 1 :(得分:0)

打印出所有出现的名称:

private static void searchArray(String[] nameList, String target) {
  boolean isFound = false;
  for (int i = 0; i < nameList.length; i++){
    if (nameList[i].equals(target)) {
        System.out.println("Name found at location: " + i);
        isFound=true;
    }

  }
  if(isFound)
     System.out.println("Sorry, name not found!"); 
}

如果您使用return语句,则不需要else语句。只说'#34;名字未找到&#34;在方法结束时,因为只有在isFound为假(即您没有找到名称)时才会到达该位置。

答案 2 :(得分:0)

如果目标是显示所有可能的匹配,您可能希望使用regex.Pattern进行不区分大小写的搜索,然后显示所有可能的匹配。

假设您使用的是名称列表,您可以执行以下操作:

List<String> names = new ArrayList<String>();

// Some code to insert names

// In your search method
for (String name : names) {
    if (Pattern.compile(Pattern.quote(criteria), Pattern.CASE_INSENSITIVE).matcher(name).find()) {
        System.out.println(String.format("Found `%s` as a possible match", name));
    }
}