Java:为什么我一直在为这个方法获取StringIndexOutOfBoundsException?

时间:2014-12-10 04:02:46

标签: java loops for-loop encode

我编写了一个静态方法,用于获取字符串并加扰它。

当你输入一个给定的字符串,例如“四分七分”时,你应该得到输出

“f rneosedvuc eroasn”,因为字符串被扰乱到下面的网格中。

row 1:       f   r n e

row 2:       o s e d v

row 3:       u c     e

row 4:       r o a s n

当我运行此方法时,我会在使用StringIndexOutOfBoundsException的行中获得s.charAt(i)。我不知道为什么会这样。无论我多少次更改for循环测试,这显然都是问题,我仍然会收到此错误。

代码:

public class Test {
public static void main(String[] args){
    System.out.println(encode("four score and seven", 4));
}
public static String encode(String s, int n){
    String finalOutput = "";
    for (int i = 0; i < n; i++){
        String output = "";
        for(int j = 0; j < s.length() - 1; i += n){
            System.out.println(s.charAt(i) + " " + i);
            output += s.charAt(i);
        }
        finalOutput += output;
    }
        return finalOutput;
    }
}

3 个答案:

答案 0 :(得分:2)

条件必须是这样的:

for(int j = 0; j < (s.length()-1) && i<s.length(); j++, i+=n)

你没有增加j ++,但是你的循环会变为无穷大。

答案 1 :(得分:0)

只需更改

for(int j = 0; j < s.length() - 1; i += n) to <br />
for(int j = 0; j < s.length() - 1 &amp;&amp; i&lt;s.length(); i += n)

答案 2 :(得分:0)

在第二个循环中,你应该以j = i开头,它会让你的代码变得简单

String finalOutput = "";
        for (int i = 0; i < n; i++) {
            String output = "";
            for (int j = i; j < s.length() ; j += n) {
                System.out.println(s.charAt(j) + " " + j);
                output += s.charAt(j);
            }
            finalOutput += output;          
        }
        return finalOutput;