應該發生什麼是當輸入-2被要求'輸入數字到decrpyt'將結束while循環,並在此之後打印result2(解密字)。相反-2產生錯誤 'java.lang.StringIndexOutOfBoundsException:字符串索引超出範圍:-2'解密時出錯while循環
如何繞過此?
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);
}
}
}
}
只是檢查是否輸入的號碼,NUM,低於零前行 'RESULT2 = sourcetext.charAt(NUM);'或使用try..catch –
仍拋出異常'java.lang.StringIndexOutOfBoundsException:字符串索引超出範圍:-2' – Button
你不能有-2作爲字符串的索引 –