gpt4 book ai didi

java - 如何在使用if条件的同时提高代码标准?

转载 作者:行者123 更新时间:2023-12-01 06:50:28 26 4
gpt4 key购买 nike

假设我想在迭代列表时检查特定条件,我使用了许多 if 条件,这将违反编码标准。我有以下带有许多 if 条件的代码,如何在不改变输出的情况下减少编码行数并提高代码质量。

请在使用 if 条件时建议我一些好的标准。

while (iterator.hasNext()) {
Row nextRow = iterator.next();
for (int colIndex = 0; colIndex < 7; colIndex++) {
if (colIndex == 0) {
Cell cell = nextRow.getCell(colIndex);
if (cell != null) {
firstName = cell.getStringCellValue();
System.out.println("First Name : "+firstName);
}
}
if (colIndex == 1) {
Cell cell = nextRow.getCell(colIndex);
if (cell != null) {
middleName = cell.getStringCellValue();
System.out.println("Middle Name : "+middleName);
}
}
if (colIndex == 2) {
Cell cell = nextRow.getCell(colIndex);
if (cell != null) {
lastName = cell.getStringCellValue();
System.out.println("Last Name : "+lastName);
}
}
if (colIndex == 3) {
Cell cell = nextRow.getCell(colIndex);
if (cell != null) {
email = cell.getStringCellValue();
System.out.println("Email : "+email);
}
}
if (colIndex == 4) {
Cell cell = nextRow.getCell(colIndex);
if (cell != null) {
password = cell.getStringCellValue();
System.out.println("Password : "+password);
}
}
if (colIndex == 5) {
Cell cell = nextRow.getCell(colIndex);
if (cell != null) {
role = cell.getStringCellValue();
System.out.println("Role : "+role);
}
}
if (colIndex == 6) {
Cell cell = nextRow.getCell(colIndex);
if (cell != null) {
status = cell.getStringCellValue();
System.out.println("Status : "+status);
}
}
}
System.out.println();
}

最佳答案

您有一个绝佳的机会进行枚举:

enum Field {

FirstName,
MiddleName,
LastName,
EMail,
Password,
Role,
Status;
}

public void test() {
while (iterator.hasNext()) {
Row nextRow = iterator.next();
Map<Field, String> values = new EnumMap(Field.class);
for (Field f : Field.values()) {
Cell cell = nextRow.getCell(f.ordinal());
if (cell != null) {
values.put(f, cell.getStringCellValue());
}
}
}
}

关于java - 如何在使用if条件的同时提高代码标准?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32452164/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com