【问题标题】:Changing Array index 0 to 1 in java在java中将数组索引0更改为1
【发布时间】:2017-11-20 21:39:03
【问题描述】:

索引 0 必须从队列中删除。你回答 总是在索引 0 上找到的对话上。队列中的所有其他呼叫必须“向前移动”一步,以便索引 1 现在应该获得索引 0,依此类推。尝试了这种方法和许多其他方法,但无法正常工作。

public static void answerCall() {
    for (int i = 0; i < customerList.length-1; i++) {
        if (customerList[i] != null  && customerList[i + 1] == null) {
            customerList[i] = null;
            counter--;
        } else if (customerList[i] != null && customerList[i + 1] != null) {
            customerList[i] = customerList[i + 1];
            customerList[i + 1] = null;
            counter--;
        }

    }

}

}

【问题讨论】:

  • 这就是为什么你应该使用集合而不是数组。
  • 我知道但我必须使用数组...
  • 为什么所有if 声明?只有循环内的语句应该是customerList[i] = customerList[i + 1]; 语句。然后你将最后一个值设置为null的循环之后。

标签: java arrays


【解决方案1】:

我相信这样的事情应该可行:

public static void answerCall()
{
    for(int i = 0; i < customerList.Length - 1; i++)
    {
        if(customerList[i+1] != null)
        {
            customerList[i] = customerList[i+1];
        }
    }
    customerList[customerList.Length] = null;
}

它只是遍历数组(最后一个值除外), 并为每个值分配下一个值。

我也不完全确定是什么

【讨论】:

    【解决方案2】:

    你不需要counter——而且int不能为null,它是0,因为它是一个原始类型:

    public static void answerCall() {
        for (int i = 0; i < customerList.length-1; i++) 
        {
            if (customerList[i + 1] == 0) {
                customerList[i] = 0;
            } else if (customerList[i + 1] != 0) {
                customerList[i] = customerList[i + 1];
            }
        }
    }
    

    【讨论】:

      【解决方案3】:

      很难理解您的问题,但这可能会有所帮助?

      Public static void answerCall() {
      /* 
      for loop iterates through list backwards moving elements forward until index 0
      */
          for (int i = 0; i < customerList.length - 1; i++) { 
              if (i != 0) {
                  customerList[CustomerList.length - i] = customerList[customerList.length - (i + 1)];
              } else {
                  customerList[0] = 0;
              }
         }
      }
      

      【讨论】:

        猜你喜欢
        • 2019-10-28
        • 2018-06-21
        • 2015-05-27
        • 1970-01-01
        • 1970-01-01
        • 2017-11-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多