0

I just started working with arrays.My code is supposed to keep asking for the user to enter words/alphabets.However,if the words entered are similar for 2 consecutive entries,the program should display a message as shown below.The following was my hypothesis to compare 2 consecutive string elements.However,my program does't work.

 import java.util.*;

public class StringArrays {
    public static void main(String[]args)
    {

        String[] list=new String[50];
        for( int i=0;i<50;i++)

        {


            Scanner a=new Scanner(System.in);
            System.out.println("Enter something: ");
            list[i]=a.next();

            if(list[i]==list[i+1])
            {
                System.out.println("Stop!");

            }
            else
            {
                System.out.println("Smart!Continue..");
            }

        }
    }
}

I'm just wondering what's the correct way to inspect 2 consecutive elements of a string array. Thanks for all your help :)

12dec1990
  • 115
  • 1
  • 9
  • 3
    Don't create scanner inside loop. Create it before and use it inside loop. Also take a look at [how-do-i-compare-strings-in-java](http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java). – Pshemo Feb 25 '15 at 03:45

2 Answers2

0

If you are at iteration i, then the value of list[i+1] will be null because you have not had a chance to input it yet. You want to compare against the last element entered, which is list[i-1].

Also beware of the edge cases. When entering item 50 at index 49, you will be checking list[50] (49 + 1 = 50), which is outside the array bounds. Similarly for list[i-1], at i = 0, i-1 will also be outside the array bounds.

To perform the comparison, you need to use the String equals() method. Comparing using == checks for the same reference, not for the same content.

mattm
  • 5,851
  • 11
  • 47
  • 77
0

The other problem with this code is that you are using == to compare strings. That is an identity comparison that may not work like you expect. Use:

list[i].equals(list[i-1]);

instead (note that I started comparing against the previous element instead of the next element as your code was written).

Kevin Day
  • 16,067
  • 8
  • 44
  • 68