>上下文:我正在构建一个接受字符串的方法,例如: "12+12"或"12/3+5*6-(12+1)" 并将其转换为如下所示的字符串列表: [12
, +, 12] 或 [12,/, 3, +, 5, *, 6, -, (, 12, +, 12, )]我想你明白了
我决定采用一种设计,即 for 循环遍历原始字符串的每个索引,并确定是否应将该索引的字符添加到列表中,即是否应该在添加数字之前查找该数字之后的另一个数字。当我编写一个 while 循环时出现问题,条件是下一个索引 (i+1) 是数字或 .(点)。问题是,当字符串中的最后一个索引是数字时,它会在高于字符串长度的索引处查找字符。唯一看起来不荒谬的方法是将其放在 try/catch 块中,如以下示例所示:"字符串 rawCalc = "12+12";
while (i < rawCalc.length()) { // loop that goes through the string index by index
String add = Character.toString(rawCalc.charAt(i)); // what is going to be added this iteration
if (anyNumberPattern.matcher(Character.toString(rawCalc.charAt(i))).matches()) { // if the character at the
// current index is a
// digit
try {
while (anyNumberPattern.matcher(Character.toString(rawCalc.charAt(i + 1))).matches()
|| Character.toString(rawCalc.charAt(i + 1)).equals(".")) { // check if the next index is
// also a digit or a point
add += Character.toString(rawCalc.charAt(i + 1)); // in that case, add that to the "add" string also
i++; // and go to the next character
}
} catch (StringIndexOutOfBoundsException e) {
}
}
i++;
refinedCalc.add(add); // add what "add" contains to the refinedCalc
}
System.out.println(refinedCalc);`
我是编程新手,但我觉得在循环时使用异常停止编码会很糟糕。毕竟,它们被称为例外,这可能意味着它们应该被 Ecxeptionical 使用。那么:谁有一个好的单行代码来阻止我的while循环检查上次迭代?
只需添加一个中断即可轻松实现停止 while 循环
while(true) {
if(stop)
break;
/*DO STUFF*/
}
您可以组合以下几个条件:
while (i + 1 < rawCalc.length() && (anyNumberPattern.matcher(Character.toString(rawCalc.charAt(i + 1))).matches() || Character.toString(rawCalc.charAt(i + 1)).equals("."))) {
因此,如果第一个条件失败,则不检查第二个条件,也不会发生异常。
删除您的try-catch StringIndexOutOfBoundsException
,然后在第一个i++
之后添加一个if
语句。
i++;
if (i > rawCalc.length()) break;
或者也许是i >= rawCalc.length()
.
您应该在内部while loop
中添加长度检查,以避免迭代超出界限。
try {
while (i < rawCalc.length()-1 && anyNumberPattern.matcher(Character.toString(rawCalc.charAt(i + 1))).matches()
|| Character.toString(rawCalc.charAt(i + 1)).equals(".")) { // check if the next index is
// also a digit or a point
add += Character.toString(rawCalc.charAt(i + 1)); // in that case, add that to the "add" string also
i++; // and go to the next character
}
} catch (StringIndexOutOfBoundsException e) {
}