java - 如何循环遍历数组来查找参数是否与数组中的元素匹配?

标签 java arrays for-loop

String[] arr = new String[3];
public static void main(String args[]){
        classname n = new classname();
        arr[0] = "bob";
        arr[1] = "Lisa";
        arr[2] = "Rob";
        n.applesEaten(bob,5)
        n.applesEaten(bob,9)
        n.applesEaten(bob,5)
        n.applesEaten(Lisa,3)
        n.applesEaten(Lisa,5)
        n.applesEaten(Rob,7)
}
public int applesEaten(String name, int apples){
        //because this method was called 3 times for bob and bob ate 5+9+5 apples,
//this method should return 19. and 8 for Lisa, 7 for Rob.
}

我尝试使用单个 for 循环遍历 arr 数组,但是,循环添加了每个人的苹果,如何才能使该方法可以为不同名称返回不同数量的苹果?

最佳答案

您需要一个映射而不是数组,如下所示:

private static Map<String,Integer> arr = new HashMap<>(  );

public static void main(String args[]){

    applesEaten("bob",5);
    applesEaten("bob",9);
    applesEaten("bob",5);
    applesEaten("Lisa",3);
    applesEaten("Lisa",5);
    applesEaten("Rob",7);
}
public static int applesEaten(String name, int apples)
{
    return arr.compute(name, (k,v) -> (v == null) ? apples : v+apples );
}

根据要求,仅使用数组解决方案[但不要这样做:)]:

private static String[] arr = new String[3];

public static void main(String args[])
{
    arr[0] = "bob";
    arr[1] = "Lisa";
    arr[2] = "Rob";
    applesEaten("bob",5);
    applesEaten("bob",9);
    applesEaten("bob",5);
    applesEaten("Lisa",3);
    applesEaten("Lisa",5);
    applesEaten("Rob",7);
}
public static int applesEaten(String name, int apples)
{

    for ( int i = 0; i < arr.length; i++ )
    {
        String[] split = arr[i].split( "-" );
        if(split[0].equals( name ))
        {
            if(split.length==1)
            {
                arr[i]=name+"-"+apples;
                return apples;
            }
            else
            {
                int newApples = (Integer.parseInt( split[1] )+apples);
                arr[i]=name+"-"+newApples;
                return newApples;
            }

        }
    }
    return 0;
}

关于java - 如何循环遍历数组来查找参数是否与数组中的元素匹配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60371176/

相关文章:

bash - 在 Bash 中使用二维数据集?

java - 用java制作一个计算器

java - Android:使用 Java 反射更改私有(private)静态最终字段

java - JSP-JSTL表仅选择表的第一行

c - 将 BST 传递给结构数组

c - 我在函数定义中犯了什么错误(C)

bash - 使用循环将单个短语替换为列表中的不同短语

java - 尝试编译Java文件时出现错误

php - in_array() 验证不起作用

c++ - 帮助我理解这个 C++ for 循环的终止参数