首页 > 解决方案 > 我需要帮助重命名数组中的元素

问题描述

我在学校做一个java项目,我们遇到了以下问题:

重命名 - 更改现有工作表的名称

public int rename(String currentName, String newName)

rename传递了两个工作表名称。currentName仅当工作表名称在列表中而工作newName表名称不在时,才应执行重命名。否则rename什么都不做(即列表不受影响)。如果currentName成功更改为newName则该方法返回重命名的工作表的索引位置。否则返回-1

这是我到目前为止所拥有的

public int rename(String currentName, String newName) {
    int i = 0;
    for (i=0; i<SheetsNames.length; i++) {
        if (SheetsNames[i].equals(currentName)) {
            SheetsNames[i] = newName;
                return i;
        }
    }
    return -1;
}

我得到了重命名部分,但我不能让它不重命名为具有相同名称的东西

标签: javaarraysrename

解决方案


遍历 SheetNames 并将 currentName 的索引的任何实例存储在一个名为 index 的变量中,同时检查 newName 是否存在于列表中。如果有 newName 的实例自动返回 -1。但是,如果列表中没有 newName,则 currentName 的索引实例将存储在索引变量中(如果存在)。如果没有,那么该函数无论如何都会返回 -1,因为这是索引初始化的内容。

public int rename(String currentName, String newName) {
    int index = -1;
    for (int i=0; i<SheetsNames.length; i++) {
        if (SheetsNames[i].equals(newName))
            return -1;
        if (SheetsNames[i].equals(currentName))
            index = i;
    }
    if (index != -1)
        SheetNames[index] = newName;
    return index; 
}

推荐阅读