Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java:为什么我一直在为这个方法获取StringIndexOutOfBoundsException?_Java_Loops_For Loop_Encode - Fatal编程技术网

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

Java:为什么我一直在为这个方法获取StringIndexOutOfBoundsException?,java,loops,for-loop,encode,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 当我运行此方法时,我会在使用s.charAt(I)的行中不断获取StringIndexOutOfBoundsExcept

我已经编写了一个静态方法,用于获取字符串并对其进行置乱

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

“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
当我运行此方法时,我会在使用
s.charAt(I)
的行中不断获取
StringIndexOutOfBoundsException
。我不知道这是为什么。无论我对for循环测试做了多少更改(这显然是个问题),我仍然会得到这个错误

代码:

公共类测试{
公共静态void main(字符串[]args){
System.out.println(编码(“四分七”,4));
}
公共静态字符串编码(字符串s,整数n){
字符串finalOutput=“”;
对于(int i=0;i
条件必须如下所示:

for(int j = 0; j < (s.length()-1) && i<s.length(); j++, i+=n)
for(int j=0;j
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)
for(int j=0;j
对于(int j=0;j
在第二个循环中,u应该以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;
String finalOutput=”“;
对于(int i=0;i
for(int j=0;jString 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;