java - 我需要帮助重命名数组中的元素
问题描述
我在学校做一个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;
}
我得到了重命名部分,但我不能让它不重命名为具有相同名称的东西
解决方案
遍历 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;
}
推荐阅读
- sql - JPA Criteria 2 嵌入了 JOIN 和它们之间的条件
- c++ - 输出中的随机换行符
- javascript - Javascript中的动画
- linux - 获取 Linux 内核中给定功能的依赖项
- c# - 如何使用从解决方案中现有基类继承的 T4 模板生成类?
- c# - 嗨,我的 2D 游戏角色传送有点高,然后他下来很慢,当我按下跳跃按钮时就像一片叶子
- compilation - 编译时无法将“.so”共享库链接到主“.c”文件
- mongodb - 日期不匹配的mongo db查询数据
- amazon-web-services - 如何使用 boto3 删除 s3 生命周期规则
- sql - SQL Server - 在多天内按分钟聚合数据