-3

Here comes my code in java :

import java.util.Scanner;

public class repetedstring 
{
    public static void main(String[] args) 
    {
      int n = 0;
      Scanner a=new Scanner(System.in);
      System.out.println("Enter the value of n:");
      n=a.nextInt();
      String s[]=new String[n];
      for (int i = 0; i <n; i++) 
      {
          s[i]=a.nextLine();    
      }
      for (int i = 0; i<n-1 ; i++) 
      {
          if(s[i]==s[i+1])
          {
              System.out.println(s[i]);
          }
          else
          {
              System.out.println("not");
          }     
    }
}

}

If I give the value for n as 5 only 4 inputs are got by the compiler and the else part is only working. Please provide me some solution.

Paul
  • 3,962
  • 2
  • 23
  • 49
  • 1
    [Open letter to students with homework problems](http://meta.softwareengineering.stackexchange.com/questions/6166/open-letter-to-students-with-homework-problems) – byxor Dec 16 '16 at 13:30
  • Could you explain a bit more? And add the expected output? – B001ᛦ Dec 16 '16 at 13:30

1 Answers1

1

After you fill up the array, change what you have to this:

ArrayList<String> strings = new ArrayList();
for(String str : s){
    if(strings.contains(str){
        System.out.println(str);
    } else {
        strings.add(str);
        System.out.println("not");
    }
}

This checks for duplicated strings anywhere in the array, not just two of the same in a row.
If you need to use arrays and can't use an ArrayList, try this instead:

for(int i = 0; i < s.length; i++){
    for(int j = i + 1; j < s.length; j++){
        if(s[i].equals(s[j]){
            System.out.println(s[i]);
        } else {
            System.out.println("not");
        }
    }
}
James McDowell
  • 1,995
  • 1
  • 11
  • 26