【问题标题】:How do I prompt a user for a name and remove that name in the array? [duplicate]如何提示用户输入名称并在数组中删除该名称? [复制]
【发布时间】:2015-09-20 13:45:25
【问题描述】:

即使我输入的名字在数组中,这段代码总是说它不在列表中。这与我设置 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));

  }

【问题讨论】:

    标签: java


    【解决方案1】:

    你应该改变你的

    if (stuName[position] == searchValue)
    

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

    原因是否则你会比较对象,两个对象总是不同的,即使它们包含相同的值。奇怪但真实;-) equalsIgnoreCase 确保您比较 String 对象的内容。您可能想查看here 了解更多详情。

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

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

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

    【讨论】:

    • 为什么它不从数组中删除找到的值?
    • 因为它没有找到任何东西?即使它会找到匹配项,您也会用第 -1 个元素覆盖数组中的第二个字符串:stuName[1] = stuName[currentSize - 1];。删除if(found) 看看你的程序崩溃了...
    • 我明白了..我怎样才能重新编写代码,以便当我搜索存储在数组中并作为匹配项返回的值时,它会删除该项目?
    • 您可以再次创建完整的字符串,或者为此使用更好的数据结构,也许是一个列表:stackoverflow.com/questions/10714233/remove-item-from-arraylist
    【解决方案2】:

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

    stuName[position].equals(searchValue)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-06-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-23
      • 1970-01-01
      • 2020-09-25
      相关资源
      最近更新 更多