我正在创建一个链接列表程序,我收到一个错误,我不知道如何解决。我知道它与我的程序上的try语句有关,但我需要帮助才能解决这个问题。到目前为止这是我的代码。
public class LinkedStringTest {
public static void main(String[] args) {
char[] array = {'L', 'u', 'k', 'e',',', ' ', 'I', ' ', 'a', 'm', ' ',
'y', 'o', 'u', 'r', ' ', 'f', 'a', 't', 'h', 'e', 'r'};
LinkedString s1 = new LinkedString(array);
for(int i = 0 ; i < s1.length(); i++) {
System.out.print(s1.charAt(i));
}
System.out.println();
try {
System.out.println(s1.charAt(20));
}
catch(ListIndexOutOfBoundsException e) { //* error #1
System.out.println(e.toString());
}
System.out.println();
LinkedString s2 = new LinkedString("Welcome, Jedi");
for(int i = 0 ; i < s2.length(); i++) {
System.out.print(s2.charAt(i));
}
System.out.println();
try {
System.out.println(s2.charAt(53));
}
catch(ListIndexOutOfBoundsException e) { //* error #2
System.out.println(e.toString());
}
try {
System.out.println(s1.substring(6, 35));
}
catch(ListIndexOutOfBoundsException e) { //* error #3
System.out.println(e.toString());
}
try {
System.out.println(s1.substring(10, 0));
}
catch(ListIndexOutOfBoundsException e) { //* error #4
System.out.println(e.toString());
}
System.out.print("Index 0 to 16 in s1: ");
LinkedString s3 = s1.substring(0, 16);
for(int i = 0; i < s3.length(); i++) {
System.out.print(s3.charAt(i));
}
System.out.println();
System.out.print("Index 4 to 10 in s1: ");
s3 = s1.substring(4, 10);
for(int i = 0; i < s3.length(); i++) {
System.out.print(s3.charAt(i));
}
System.out.println();
LinkedString s4 = s2.concat(new LinkedString(" May the force be with you."));
for(int i = 0; i < s4.length(); i++) {
System.out.print(s4.charAt(i));
}
System.out.println();
char[] myArray = s1.toCharArray();
for(int i = 0; i < myArray.length; i++) {
System.out.println(myArray[i]);
}
LinkedString s5 = new LinkedString("This is a new linked string");
System.out.println(s5.toString());
}
}
更新: 忘了发布错误。在这里。
LinkedStringTest.java:13: error: exception ListIndexOutOfBoundsException is never thrown in body of corresponding try statement
catch(ListIndexOutOfBoundsException e) {
^
LinkedStringTest.java:26: error: exception ListIndexOutOfBoundsException is never thrown in body of corresponding try statement
catch(ListIndexOutOfBoundsException e) {
^
LinkedStringTest.java:32: error: exception ListIndexOutOfBoundsException is never thrown in body of corresponding try statement
catch(ListIndexOutOfBoundsException e) {
^
LinkedStringTest.java:38: error: exception ListIndexOutOfBoundsException is never thrown in body of corresponding try statement
catch(ListIndexOutOfBoundsException e) {
^
4 errors
答案 0 :(得分:1)
charAt()
会引发IndexOutOfBoundsException
而不是ListIndexOutOfBoundsException
。同样适用于substring()
。
密钥在错误消息中,其中显示:
错误:异常ListIndexOutOfBoundsException永远不会抛出
这表示您正在尝试捕获未在try块中抛出的异常。