当被要求'输入数字到decrpyt'时输入-2将结束while循环,然后打印结果2(解密的单词)。而是-2产生错误 'java.lang.StringIndexOutOfBoundsException:字符串索引超出范围:-2'
如何绕过这个?
import java.util.Scanner;
public class Decrypt {
public static void main(String[] args) {
Scanner sc;
int result, input2, num, end = -2;
String word, sourcetext, answer, encrypt = "1", decrypt="2";
char input, result2;
sc = new Scanner(System.in);
System.out.println("please enter sourcetext");
sourcetext = sc.nextLine();
System.out.print("Would you like to 1: encrypt, or 2: decrypt?");
answer = sc.next();
System.out.println("please enter numbers to decrypt");
while (answer.equals(decrypt)) {
num = sc.nextInt(); // number to decrypt
result2 = sourcetext.charAt(num); // num decrypted
if (num <= end) { // int end = -2
System.out.print(result2);
}
}
}
}
答案 0 :(得分:0)
当输入-2时,它会将其传递给charAt
,这会引发异常,因为字符串中没有-2索引。您应该将if (num <= end)
块移动到while循环的开头,并将其余块放入else
块。
像这样:
if (num <= end){
System.out.print(result2);
} else {
num = sc.nextInt(); // number to decrypt
result2 = sourcetext.charAt(num); // num decrypted
}