Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/346.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/algorithm/11.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 简单字符串数组上的越界错误_Java_Runtime Error - Fatal编程技术网

Java 简单字符串数组上的越界错误

Java 简单字符串数组上的越界错误,java,runtime-error,Java,Runtime Error,我试图创建一个方法,将一个字符串分成4个组,并且不断得到一个越界错误。我不明白它是从哪里来的,有没有更简单的方法来实现这一点,或者是什么导致了错误 编辑:已解决的坏括号表示int MAX未分配正确的值 有关守则 public void ColumnCode(String plaintext) { System.out.println("Please enter the number of columns you want"); int columns = slave.getNum

我试图创建一个方法,将一个字符串分成4个组,并且不断得到一个越界错误。我不明白它是从哪里来的,有没有更简单的方法来实现这一点,或者是什么导致了错误

编辑:已解决的坏括号表示int MAX未分配正确的值

有关守则

public void ColumnCode(String plaintext) {
    System.out.println("Please enter the number of columns you want");
    int columns = slave.getNum();

    int MAX = (plaintext.length()-1/columns)+1; //number of times to iterate the for loop
    String[] groups = new String[MAX];

    for(int i = 0; i < MAX; i++) {
        if((4*i)+4 > plaintext.length()) groups[i] = plaintext.substring(4*i);
        else groups[i] = plaintext.substring(4*i, 4*(i+1));
        System.out.println(groups[i]);
    }
}

你的括号放错地方了


它应该是
int MAX=(plaintext.length()-1)/columns+1

错误是由此行引起的:
intmax=(明文.length()-1/列)+1

计算1/列后,运算顺序将在括号内进行减法运算


这会导致内部差异变为(在4列的情况下)
plaintext.length()
-0.25,实际上使最大值大于数组大小,从而导致错误。

啊,这是有道理的。另一方面,它不是“plaintext.length()-0”吗,因为它被分配给了一个int?您得到了边界错误的索引,因为在上一次迭代中,您假设数组中有4个元素,但数组中只填充了1个元素(“E”)。
Now please enter the plaintext to be encrypted: 
THIS IS A MESSAGE
Please enter the number of columns you want
4
THIS
 IS 
A ME
SSAG
E
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -3
    at java.lang.String.substring(Unknown Source)
    at Cryptopher.ColumnCodeClass.ColumnCode(ColumnCodeClass.java:26)
    at Cryptopher.mainFile.encrypt(mainFile.java:86)
    at Cryptopher.mainFile.runTheProgram(mainFile.java:55)
    at Cryptopher.mainFile.main(mainFile.java:36)