gpt4 book ai didi

java - 在java中比较2个数组的每个值,对于每个相同的值+4,如果不是-1

转载 作者:行者123 更新时间:2023-12-02 10:52:46 24 4
gpt4 key购买 nike

我们有 2 个数组,有一些元素。比较相同索引处的两个数组元素,如果等于+4,如果不等于-1。

示例:

array1=[a b a b], array2=[a a b b]

explanation:
array1[0]==array2[0] //+4
array1[1]!=array2[1] //-1
aarray1[2]==array2[2] //+4
aarray1[3]!=array2[3] //-1
OUTPUT//6**

我的代码:

import java.util.Scanner;
class Solution
{
public static int scoreExam(String[] correct, String[] student)
{
int count=0;
for (int i=0;i<correct.length ;i++ )
{
for (int j=0;j<student.length ;j++ )
{
if(i==j)
{
if(correct[i]==student[j])
{
count=count+4;
}
else if(correct[i]!=student[j])
{
count=count-1;
}
}
}
}
return (count);
}

public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
String[] array1String,array2String;
String[] array2;
int n=Integer.parseInt(sc.nextLine());
array1String=sc.nextLine().split("//s+");
array2String=sc.nextLine().split("//s+");

array2=new String[array2String.length];
for (int i=0;i<array2String.length ;i++ )
{
if (array2String[i].equals("blank"))
{
array2[i]="";
}
else
{
array2[i]=array2String[i];
}

}

System.out.println(scoreExam(array1String, array2));
}
}

最佳答案

尽管这是一个关于比较 String 的重复问题,但我认为 Stream 也非常适合这种情况;您可以使用 IntStream 并将每个元素映射到 4(如果答案匹配),否则映射到 -1,然后简单地返回总和:

IntStream.range(0, correct.length)
.map(i -> correct[i].equals(student[i]) ? 4 : -1)
.sum();

关于java - 在java中比较2个数组的每个值,对于每个相同的值+4,如果不是-1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52027352/

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