[英]How can I loop through an array to find if the parameter matches the element in the array?
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.
}
I tried using a single for-loop that traverses through arr array, however, the loop adds everyone's apple, how do I make it so that this method can return the different amount of apples for different names?我尝试使用遍历 arr 数组的单个 for 循环,但是,该循环添加了每个人的苹果,我该如何制作才能使此方法可以为不同的名称返回不同数量的苹果?
You need a Map instead of an Array, like this:你需要一个 Map 而不是一个数组,像这样:
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 );
}
As requested, an Array only solution [But don't do this :)]:根据要求,仅使用 Array 解决方案 [但不要这样做 :)]:
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.