0

We have 2 array,having some element. Comparing both array element at same index, if equal +4 and -1 if not.

Example:

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**

My code:

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));
}
}
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • Please click [edit] and add a question to your explanation of your task and your code. – Sergey Kalinichenko Aug 26 '18 at 14:46
  • Hi! Note that there's no need for your `else if`. Just use `else`. If the first `if`'s condition (are they equal?) is false, they're not equal. – T.J. Crowder Aug 26 '18 at 14:51
  • Welcome to Stack Overflow! Please have a look around, and read through the [help], in particular [*How do I ask a good question?*](/help/how-to-ask) You haven't said what's wrong with the code you've shown, e.g., what isn't working the way you expect. We've guessed that you're not getting the correct output, but it's important to be clear when asking questions. [Jon Skeet's question checklist](https://codeblog.jonskeet.uk/2012/11/24/stack-overflow-question-checklist/) is also useful reading. – T.J. Crowder Aug 26 '18 at 14:54

1 Answers1

2

Even though this is a duplicate question about comparing Strings, I think a Stream would also be perfect for this scenario; you can use an IntStream and map each element to 4 if the answers match and -1 otherwise, and then simply return the sum:

IntStream.range(0, correct.length)
         .map(i -> correct[i].equals(student[i]) ? 4 : -1)
         .sum();
Jacob G.
  • 28,856
  • 5
  • 62
  • 116