如何提示用户输入名称并删除数组中的名称?

时间:2015-07-02 21:00:54

标签: java

即使我输入的名称在数组中,这段代码总是说它不在列表中。它与我设置的searchValue等于什么有关吗?

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));

  }

2 个答案:

答案 0 :(得分: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显示逗号分隔列表可确保您比较String对象内容。您可能需要查看here以获取更多详细信息。

但您的代码还有另一个问题:

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

这将尝试用元素-1覆盖第二个元素(数组计数从0开始)(currentSize等于0,0-1为-1)。这肯定会因IndexOutOfBounds异常而崩溃。

答案 1 :(得分:0)

==用于比较原始数据类型值和对象引用。要比较字符串值,请使用

stuName[position].equals(searchValue)