下面的代碼不起作用,因爲它使用模數對負數進行計算。所以我必須解析值爲2d數組聲明爲BigInteger而不是int。將一個bigInteger值添加到二維數組中
BigInteger bi2, bi3;
int det=(key[0][0] * key[1][1])-(key[0][1] * key[1][0]);
BigInteger bi1 = new BigInteger(String.valueOf(det));
bi2 = new BigInteger("26");
bi3 = bi1.modInverse(bi2);
int inverse= bi3.intValue();
key[0][0] = inverse * key[0][0];
key[0][1] = inverse * key[0][1];
key[1][0] = inverse * key[1][0];
key[1][1] = inverse * key[1][1];
key2[0][0] = key[1][1];
key2[1][1] = key[0][0];
key2[0][1] = -key[0][1];
key2[1][0] = -key[1][0];
的問題是在這裏: 其打印錯誤的答案爲每個計算,因爲它需要鄰BigInteger的使用,因爲負值INETGER代替。
key[0][0] = key2[0][0] % 26;
key[0][1] = key2[0][1] % 26;
key[1][0] = key2[1][0] % 26;
key[1][1] = key2[1][1] % 26;
此後,我想對這個BigIntegers做一些計算。然而,計算將只包括整數。所以之後我必須將數組中的BigInteger轉換爲整數。
其餘代碼:
for (int i = 0; i < str.length(); i++) {
for (int j =0; j< alphabet.size() ; j++){
if (alphabet.get(j) == str.charAt(i)) {
int index = alphabet.indexOf(str.charAt(i));
store.add(index);
}
}
}
System.out.println(Arrays.toString(store.toArray()));
for (; k<store.size(); k++){
sp2 = sp +1;
int n2=0;
int n1 = 0;
if (sp==store.size()-1){
n1 = store.get(sp);
if (sp2> store.size()-1){
n2 = 23;
}
if(sp2 < store.size()) {
n2 = store.get(sp2);
}
fn1 = ((key[0][0] * n1) + (key [0][1] * n2))% 26;
fn2 = ((key[1][0] * n1) + (key [1][1] * n2))%26;
conversion.add(fn1);
conversion.add(fn2);
sp+=2;
}
if (sp > store.size() -1){
break;
}
else{
n1 = store.get(sp);
n2 = store.get(sp2);
fn1 = ((key[0][0] * n1) + (key [0][1] * n2))% 26;
fn2 = ((key[1][0] * n1) + (key [1][1] * n2))%26;
conversion.add(fn1);
conversion.add(fn2);
sp+=2;
}
}
System.out.println(Arrays.toString(conversion.toArray()));
List<Character> encrypted = new ArrayList();
for (int i=0; i<conversion.size(); i++){
int num = conversion.get(i);
char letter = alphabet.get(num);
encrypted.add(letter);
}
System.out.println(Arrays.toString(encrypted.toArray()));
錯誤消息:異常在線程 「主」 java.lang.ArrayIndexOutOfBoundsException:-8
的錯誤是這樣(結束前4行): 炭letter = alphabet.get(num);
提供[MCVE](http://stackoverflow.com/help/mcve) –
您是否厭煩閱讀文檔? – redFIVE
+所以至少keytest和myInteger的類型。以及你面對的確切錯誤。並從http://www.tutorialspoint.com/java/math/biginteger_valueof.htm –