gpt4 book ai didi

java - 在 FOR 循环中使用大量 IF 语句

转载 作者:行者123 更新时间:2023-11-29 09:36:19 25 4
gpt4 key购买 nike

有没有更简单的方法来完成这样的任务,我不必使用大量 IF 语句。

for (int i = 0; i < registration.length(); i++) {
char numberFromReg = registration.charAt(i);
String yearFromReg = "";
if (numberFromReg == '1') {
yearFromReg += "1";
} else if (numberFromReg == '2') {
yearFromReg += "2";
} else if (numberFromReg == '3') {
yearFromReg += "3";
} else if (numberFromReg == '4') {
yearFromReg += "4";
} else if (numberFromReg == '5') {
yearFromReg += "5";
} else if (numberFromReg == '6') {
yearFromReg += "6";
} else if (numberFromReg == '7') {
yearFromReg += "7";
} else if (numberFromReg == '8') {
yearFromReg += "8";
} else if (numberFromReg == '9') {
yearFromReg += "9";
} else if (numberFromReg == '0') {
yearFromReg += "0";
}
}

最佳答案

似乎您只需要数字,所以您可以将replaceAll 用作

yearFromReg  = registration.replaceAll("\\D","");

\\D :表示非数字值,因此 replaceAll 将从字符串中删除所有非数字值。

关于java - 在 FOR 循环中使用大量 IF 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48462699/

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