我正在尝试创建一个将String分成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]);
}
}
示例错误消息:
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)
答案 0 :(得分:1)
你有一个错误的支架。
应为int MAX = (plaintext.length()-1)/columns+1
答案 1 :(得分:1)
错误是由此行引起的:
int MAX = (plaintext.length()-1/columns)+1;
在评估 1 /列之后,操作顺序将在括号内进行减法。
这导致内部差异变为(在4列的情况下)plaintext.length()
- 0.25,实际上使MAX大于数组大小,从而导致错误。