-1

Even though the name I entered is in the array, this piece of code always says it's not on the list. Does it have to do with what I set searchValue equaled to?

String[] stuName = new String[MAX_ON_LIST];

  int currentSize = 0;

  for (int i = 0; i < stuName.length; i++) {

           stuName[i] = JOptionPane.showInputDialog("Enter student name:");

  }

  String searchValue = JOptionPane.showInputDialog("Enter a name:");;
  int position = 0;
  boolean found = false;

  while (position < stuName.length && !found) {
     if (stuName[position] == searchValue) {
        found = true;
     }
     else {
        ++position;
     }
  }
  if (found) {
     stuName[1] = stuName[currentSize - 1];
     --currentSize;

     JOptionPane.showMessageDialog(null, Arrays.toString(stuName));
  }
  else {
     JOptionPane.showMessageDialog(null, "Name not on list");
     JOptionPane.showMessageDialog(null, Arrays.toString(stuName));

  }
dan
  • 127
  • 9

2 Answers2

1

You should change your

if (stuName[position] == searchValue)

to

if (stuName[position].equalsIgnoreCase( searchValue ) )

The reason is that otherwise you would be comparing objects, and two object are always different even if they contain the same value. Strange but true ;-) equalsIgnoreCase ensures that you compare the String objects content. You might want to have a look here for more details.

But there is another problem in your code:

if (found) {
     stuName[1] = stuName[currentSize - 1];
     --currentSize;

This will try to overwrite the second element (array count starts at 0) with element -1 (currentSize equals 0, 0-1 is -1). This will certainly crash with an IndexOutOfBounds exception.

Marged
  • 10,577
  • 10
  • 57
  • 99
  • Why doesn't it remove the found value from the array though? – dan Jul 02 '15 at 21:13
  • Because it does not find anything ? And even if it would find a match you would overwrite the second String in your array with the -1th element: `stuName[1] = stuName[currentSize - 1];`. Remove the `if(found)` and see your program crash ... – Marged Jul 02 '15 at 21:18
  • I see..how can I rework the code so that when I search for a value that was stored in the array and comes back as a match it removes that item? – dan Jul 02 '15 at 21:27
  • you could either create the complete string again or use a better data structure for this, perhaps a List: http://stackoverflow.com/questions/10714233/remove-item-from-arraylist – Marged Jul 02 '15 at 21:31
0

== is used to compare primitive data type values and object references. To compare string values, use

stuName[position].equals(searchValue)
BoDidely
  • 504
  • 3
  • 13