0

This a java program for finding duplicates in two string arrays.

import java.util.*;
public class session
{
    public static void main(String[] args) 
    {
        int flag=0;
        Scanner s = new Scanner(System.in);
        System.out.println("Enter the number of students in session 1 and session 2");
        int nk= s.nextInt();
        int ng= s.nextInt();
        String[] ses1 = new String[nk];
        String[] ses2 = new String[ng];
        System.out.println("Enter the registration nos. for session 1");
        for(int i = 0; i < nk; i++)
        {
           ses1[i] = s.nextLine();
        }
        System.out.println("Enter the registration nos. for session 2");
        for(int i = 0; i < ng; i++)
        {
          ses2[i] = s.nextLine();
        }
        for(int i = 0; i < nk; i++)
        {
            for(int j = 0; j < ng; j++)
            {
                if(ses1[i].equals(ses2[j]))
                {
                    flag=1;
                }
            }
        }
        if(flag==0)
            System.out.println("No Duplicates");
        else
            System.out.println("Error, There are duplicates");
    }
}

The first for loop runs for nk-1 cycles not nk cycles. Is there a rule involving multiple for loops?

  • 1
    the first for loop runs from 0 to nk-1 which is nk number of times – RAZ_Muh_Taz Feb 17 '21 at 18:24
  • 1
    Your first for loop, `for(int i = 0; i < nk; i++)`, will run `nk` cycles barring any JRE bugs. Works fine on my machine. Do keep in mind that `i` will have a value of `nk - 1` on the last cycle, though, because you break the loop when `i < nk`, so when `i` equals `nk`, your condition is already false. – Charlie Armstrong Feb 17 '21 at 18:25
  • The problem is that after you read the number of students in the second session the scanner cursor is just after the number, but **before** the end of line. Then the first nextLine() method in the first loop reads the empty string followed by the end of the line. So the first item in ses1 array gets empty string. You need to use s.nextLine() once before the first loop to skip the end of line. Also, check [this topic](https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-or-nextfoo) – Alex Feb 17 '21 at 18:32
  • @Alex Thanks..it worked!! – Glenn Varghese George Feb 17 '21 at 18:44

0 Answers0