【问题标题】:Removing elements from an array in JavaJava从数组中删除元素
【发布时间】:2022-01-13 21:14:18
【问题描述】:
public void removeElement( String candidate ) {
    
    // hitta elementet som ska tas bort och placera det sist i arrayen
    for( int i = 0; i < carRegister.length; i++ ) {
        String s = carRegister[i];
        if( s.equals( candidate ) ) {
            // byt plats med sista elementet
            String temp = carRegister[carRegister.length-1];
            carRegister[carRegister.length-1] = s;
            carRegister[i] = temp;
        }           
    }
    
    
    // Ta bort elementet genom att kopiera över alla utom sista elementet till en ny array
    String[] tempArray = new String[carRegister.length-1];
    for( int i = 0 ; i < carRegister.length-1; i++ ) {
        tempArray[i] = carRegister[i];
    }
    
    // den nya arrayen tilldelas arrayen carRegister
    carRegister = tempArray;
}

我的代码问题是,如果用户输入(候选)与数组中的任何元素都不匹配,我找不到阻止从第二个 for 循环复制的方法。如您所见,即使输入是“特斯拉”,它也会删除马自达。在这种情况下,我不知道如何阻止它删除数组中的最后一个元素。

【问题讨论】:

  • 为什么Mazda 被移动到第一个索引?在截断之前在末尾存储 Volvo 有什么意义?为什么不在if 内复制?
  • 不幸的是,这是我打算使用的布局。执行程序希望这样。但是为了回答您的第一个问题,马自达被移至第一个索引,因为它与沃尔沃交换了位置。所以沃尔沃被移到最后一个索引,马自达第一个。

标签: java arrays


【解决方案1】:

为什么不创建一个变量来存储您是否找到了候选人?然后,如果变量说您没有找到它,则可以避免第二个循环。例如,

   ...
   boolean foundCandidate = false; // initialized to "did not find it" 
   for( int i = 0; i < carRegister.length; i++ ) {
       String s = carRegister[i];
       if( s.equals( candidate ) ) {
          // changed if found
          foundCandidate = true;
          ...

   // now, you can avoid this loop (and modifying carRegister) if it is not necessary
   if( foundCanidate) {
      ...
   }

【讨论】:

  • 实现了你的代码,它仍然有同样的问题,它仍然复制马自达。
  • 不,它没有:ideone.com/12LK87
  • 嗯,非常抱歉,我一定错过了一些东西,因为我按照你现在的方式实现了它,但它没有用,也许我错过了一个大字母或什么的。总之非常感谢你吐槽!它现在工作正常..
猜你喜欢
  • 2010-10-13
  • 2016-05-17
  • 2011-10-31
  • 1970-01-01
  • 2019-08-23
  • 2014-04-21
  • 2017-08-08
相关资源
最近更新 更多