【问题标题】:Searching through an array for a name with a for loop使用 for 循环在数组中搜索名称
【发布时间】:2019-10-31 17:34:37
【问题描述】:

我需要帮助设计一个 for 循环,如果找到则返回该名称,如果未找到则返回未找到的请求名称。我需要这样做,而无需多次重复未找到的循环。

我尝试了各种 if、else if 和 else 语句。我还尝试了 for 循环内的 do while 循环,并尝试在循环外执行 not found 语句

    String[] values = new String[12];
    int name = 1;

    // Initialize Scanner
    java.util.Scanner input = new java.util.Scanner(System.in);

    // Create loop for name input 
    for (int i = 0; i < values.length; i++)
    {
        System.out.print("Enter in " + " the name of friend " + name++ + ": ");
        values[i] = new String(input.next());
        if (values[i].equalsIgnoreCase("zzzz")) 
    {
        break;
    }
    }

    // Create loop for name output
    System.out.println("\n" + "The names of your friends are: ");
    for (int i = 0; i < values.length; i++) 
    {
        if (values[i].equalsIgnoreCase("zzzz")) 
    {
        break;

    }
        else 
    {
        System.out.println(values[i]);
    }
    }

    // Search for the name
    boolean found = false;
    System.out.print("\n" + "Enter in the name of the friend you would like to find: ");
    String find = input.next();
    for(int i = 0;i < values.length && !found;++i) 
    {
        if (find.equalsIgnoreCase(values[i]))
        {
        System.out.println("\n" + "Your friend " + find + " was found");
        found = true;
        break;
        }
        else if (find != values[i] && (found = false))
        { 
        System.out.println("\n" + "Your friend " + find + " was not found" );
        break;
        }
    } 

    }
}   

我希望 not found 语句不会在循环中重复多次,直到找到实际名称。如果该名称在数组中不存在,则应搜索整个数组并返回未找到。

【问题讨论】:

  • 那你为什么把你的朋友没有找到语句放在循环中呢?如果你在循环之后移动它并简单地检查 found == false 你会知道整个数组之后
  • 我按照你的指示做了,把它放在循环之外 - 它工作得很好! if (find.equalsIgnoreCase(values[i])) { System.out.println("\n" + "你的朋友 " + find + " 被发现");找到=真;休息; } } if (found == false) { System.out.println("\n" + "你的朋友 " + find + " 没找到" ); }

标签: java arrays loops find


【解决方案1】:

看看我的尝试。当我们遍历数组以确保我们不会错过匹配时,我已将所有元素转换为小写。例如,如果我们搜索 "tom" 并且在我们有 "Tom" 的数组中匹配会被错过。

import java.util.Scanner;


public class Main {


    static Scanner input = new Scanner(System.in);

    public static void main(String[] args) {

        boolean foundFlag = false;
        String[] values = new String[12];

        //Populate array
        for(int i = 0, x = 1; i < values.length; i ++, x ++)
        {
            System.out.print("Enter name of friend " + x + ": " );
            String name = input.next();
            values[i] = name;
        }

        //Output all elements of the array
        System.out.println("\n" + "The names of your friends are: ");
        for(String x : values)
        {
            System.out.println(x);
        }

        //Find a friend
        System.out.print("\n" + "Enter in the name of the friend you would like to find: ");
        String find = input.next();


        //Iterate through array and check if Friend inside.
        for(int i = 0; i < values.length; i ++)
        {
            if(values[i].toLowerCase().equals(find.toLowerCase()))
            {
                foundFlag = true;
                break;
            }

        }

        //If friend in the array flag will be True, else flag will remain false.
        if (foundFlag)
        {
            System.out.println("Friend " + find + " found");
        }
        else
        {
            System.out.println("Friend " + find + " not found");
        }

    }
}

【讨论】:

    【解决方案2】:

    只需创建一个函数来进行搜索:

    public boolean findName(String[] items, String name) {
      if (items == null || items.length == 0 || name == null || name.trim().isEmpty()) return false;
      for(int i = 0; i < items.length; i++) {
        if (items[i].equalsIgnoreCase(name.trim())) {
          return true;
        }
      }
    
      return false;
    }
    

    那么你需要在哪里找朋友:

    boolean exists = findName(values, "Foo Bar");
    if (exists) {
      System.out.println("Friend exists");
    } else {
      System.out.println("Friend does not exists");
    }
    

    【讨论】:

    • 这似乎是比我做的更清洁和更有效的方式!我将把它整合到程序中。非常感谢您的推荐。
    【解决方案3】:

    您也可以使用 java 8 流:

    boolean found = Stream.of(values)
        .anyMatch(value -> value.equalsIgnoreCase(name));
    

    【讨论】:

    • 这也是一种很好的搜索方式,但我的课堂上没有讨论过,所以我无法使用它。不过还是谢谢推荐!我一定会更彻底地研究这种方法!
    【解决方案4】:

    尝试使用此代码:

        // Search for the name
            boolean found = false;
            System.out.print("\n" + "Enter in the name of the friend you would like to find: ");
            String find = input.next();
            for(int i = 0;i < values.length && !found;++i) 
            {
                if (find.toLowerCase().equals(values[i].toLowerCase()))
                {
                System.out.println("\n" + "Your friend " + find + " was found");
                found = true;
                break;
                }
    
            } 
    if(!found){
    
                System.out.println("\n" + "Your friend " + find + " was not found" );
    
    
    }
    
            }
    

    【讨论】:

    • 这就是我选择编写代码的方式!除非我这样做了 if (found == false) { System.out.println("\n" + "Your friend " + find + " was not found" ); }
    • 你的方式看起来稍微干净一些。
    猜你喜欢
    • 1970-01-01
    • 2013-08-28
    • 1970-01-01
    • 2021-04-03
    • 1970-01-01
    • 2020-09-08
    • 1970-01-01
    • 2016-05-21
    • 2015-06-13
    相关资源
    最近更新 更多