如何解决此错误:java.lang.ArrayIndexOutOfBoundsException:4
import java.io.IOException;
import java.util.Random;
import java.util.Scanner;
public class Test{
public static void main(String[] Args){
Test ts= new Test();
ts.interphace();
}
public void interphace(){
char option = 0 ;
Test ts= new Test();
System.out.println("Type E for encryption and D for decryption (In caps)");
try {
option = (char)System.in.read();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
switch(option){
case 'E':
ts.encrypt();
break;
case 'D':
ts.decrypt();
break;
default:
System.out.println("Option Invalid");
}
}
public void encrypt(){
//Gives the pcode
Test ts= new Test();
System.out.println("Encrypt method initiated");
System.out.println("Please enter the String to be encrypted");
Scanner sc = new Scanner(System.in);
String toben = sc.next();
System.out.println("Your String: "+ toben);
Random pcodegen = new Random();
int pcode = pcodegen.nextInt(64);
System.out.println("Your pcode is: "+pcode);
char unen[]=toben.toCharArray();
int unenint[]= new int[unen.length];
char en[]= new char[unen.length];
for(int i = 0;i<=unen.length;i++){
unenint[i]=ts.CharToInt(unen[i]);
}
for(int i = 0;i<=unen.length;i++){
if(unenint[i]>64)
unenint[i]-=pcode;
else unenint[i]+=pcode;
}
for(int i = 0;i<=unen.length;i++){
en[i]=ts.IntToChar(unenint[i]);
}
String encrypted = new String(en);
System.out.println("Encrypted String: "+encrypted);
}
public void decrypt(){
//Dont forget to enter the pcode
}
public int CharToInt(char ch){
int s = (int)ch;
return s;
}
public char IntToChar(int i){
char ch = (char)i;
return ch;
}
}
会发生什么是在选择该选项后,加密方法被激活。之后它会要求你输入字符串。 将数组unen中的字符转换为unenint(所以我可以用ASCII形式操作它们)时会出现问题,它会给我那个错误。 我知道代码不是很好,因为我是新手。 请紧急给我解决方案。 在此先感谢。如何解决此错误:java.lang.ArrayIndexOutOfBoundsException:4
在所有的for
循环中,通过包含=
来循环迭代过多。尝试使用这种策略:
for (int i = 0; i < unen.length; i++) {
请记住,数组索引0
,所以如果你有长度10的阵列,它通过9
包容有0
可用的指标。 =
在for
循环中有效,您将超过可用的索引。
感谢您的解释。 – NobleSiks 2013-02-20 09:43:18
你的循环
for(int i = 0;i<=unen.length;i++){
和
for(int i = 0;i<=unen.length;i++){
应该使用<
代替<=
java.lang.ArrayIndexOutOfBoundsException: 4
指4
位置值是找不到的,这样你就可以改变你的for循环:
for(int i = 0;i<unen.length;i++) //siutable for your situation
或者
for(int i = 1;i<=unen.length;i++)
变化
for(int i = 0;i<=unen.length;i++){
到
for(int i = 0;i<unen.length;i++){
到处
试试这个
for(int i = 0;i<=unen.length-1;i++)
数组索引总是从0开始,所以如果u有4个字符在unen这意味着unen最大的指数是3,你可以在这里看到
[0,1,2,3]
我建议使用
for(int i = 0;i<=unen.length-1;i++)
,因为如果ü尝试
for(int i = 0;i<unen.length;i++)
这意味着在接触最大指数时,algortihm会再检查一次,并浪费你的处理器,如果超出,它将停止。
的意思而如果u使用
for(int i = 1;i<=unen.length;i++)
你会在情况下失去了0
指数也许ü需要它
非常感谢。有效。很好的解释。我忘了数组索引从0开始。* facepalm * – NobleSiks 2013-02-20 09:42:40
我欢迎兄弟,所以请加1 ROFTL :)) – shadrachJabonir 2013-02-20 14:47:46
在所有的在加密方法循环,改变从' 2013-02-20 06:23:03