問題代碼如下,如果您需要整個主要方法來幫助我,請詢問。該代碼符合但未按預期運行。如果數字超出/大於源文本的最後一個位置(這是用戶輸入的字符串),我試圖使代碼報告返回一個感嘆號,因此無法預定義該長度。異常是'StringIndexOutOfBoundsException'字符串索引超出範圍異常,在if else語句上
TDLR num是一個int,sourcetext是一個字符串,兩者都是輸入。例外:當代碼輸出'!'時代替。
import java.util.Scanner;
public class Temp {
public static void main(String[] args) {
Scanner sc;
int result, num= 0, end = -2, temp, infolost, count;
String word, sourcetext, answer, space= " ";
String sourcetext2, temp2;
char input, result2, chalost;
sc = new Scanner(System.in);
System.out.println("please enter sourcetext");
sourcetext = sc.nextLine(); // user inputs source text
sourcetext = sourcetext.toLowerCase(); // converts sourcetext into lowercase
System.out.print("Would you like to 1 encrypt, or 2 decrypt?");
answer = sc.next(); // user inputs choice
if (answer.equals("1")||(answer.equals("encrypt"))) {
System.out.println("Please enter at least one word to encrypt");
word = sc.next(); // user inputs one word
for (int i= 0; i < word.length(); i++) {
temp = sourcetext.indexOf(word.charAt(i)); // uses index to convert char positions int num
System.out.print(space + temp + space);
}
System.out.print(space + end);
}
else if (answer.equals("2")||(answer.equals("decrypt"))) {
System.out.println("Please enter digits, with one space between each. End with -2");
while (num > -2) {
num = sc.nextInt(); // num to decrypt
if (num > -2) {
result2 = sourcetext.charAt(num); // num converted into characters
System.out.print(result2);
} else if (num > sourcetext.length()) {
System.out.print("!");
} else if (num<0) {
System.out.print("end");
}
}
}
}
}
當您嘗試訪問不在字符串範圍內的索引時,會發生完整代碼'StringIndexOutOfBoundsException'。 –
您需要提供完整的代碼,可能還有堆棧跟蹤。 – Areca
您需要學習解釋堆棧跟蹤並使用調試器,而不是要求我們爲您調試代碼。 – Raedwald