Java:找不到循环结束这个循环的好方法

时间:2018-04-06 11:39:20

标签: java

上下文:我正在构建一个带有字符串的方法,例如: “12 + 12”或“12/3 + 5 * 6-(12 + 1)” 并将其转换为字符串列表,如下所示: [12,+,12]或[12,/,3,+,5,*,6, - ,(,12,+,12,)]

我认为你有了这个想法

我决定使用一个设计wherr for循环遍历原始字符串的每个索引,并确定是否应将该索引的字符添加到列表中是否应该在添加它之前在数字后面查找另一个数字。当我写一个while循环时出现问题,条件是下一个索引(i + 1)是数字还是数字。 (点)。问题是,当字符串中的最后一个索引是数字时,它会在索引处查找高于字符串长度的字符。唯一看起来不太荒谬的方法是将它放在try / catch块中,如下例所示:`String 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);`

我是编程新手,但我觉得使用异常停止while循环是不好的编码。毕竟它们被称为例外,这可能意味着它们应该被用于Ecxeptionally。那么:谁有一个很好的单行程来阻止我的while循环检查最后一次迭代?

4 个答案:

答案 0 :(得分:0)

只需添加一个中断

即可轻松实现停止while循环
while(true) {
   if(stop) 
     break;

   /*DO STUFF*/
}

答案 1 :(得分:0)

您可以结合以下几个条件:

while (i + 1 < rawCalc.length() && (anyNumberPattern.matcher(Character.toString(rawCalc.charAt(i + 1))).matches() || Character.toString(rawCalc.charAt(i + 1)).equals("."))) {

因此,如果第一个条件失败,则不检查第二个条件,并且不会发生异常。

答案 2 :(得分:0)

您应该在内部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) {

            }

答案 3 :(得分:0)

在第一次try-catch StringIndexOutOfBoundsException添加i++声明后移除if

i++;
if (i > rawCalc.length()) break;

或者也许是i >= rawCalc.length()

相关问题