我不断地得到
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 3, Size: 3
at java.util.ArrayList.rangeCheck(Unknown Source)
at java.util.ArrayList.get(Unknown Source)
at hartman.ShortestString.printShortestString(ShortestString.java:40)
at hartman.ShortestString.main(ShortestString.java:28)我该如何解决这个问题?
package hartman;
import java.util.ArrayList;
import java.util.Scanner;
public class ShortestString {
public static void main(String[] args) {
System.out.printf("WELCOME TO SHORTEST STRING\n\n");
System.out.printf("Type \".\" when done entering data.\n\n");
ArrayList<String> myArray = new ArrayList<>();
Scanner keyboard = new Scanner(System.in);
boolean keepAsking = true;
while (keepAsking) {
System.out.printf("Enter string: ");
String userInput = keyboard.nextLine();
if (userInput.equals(".")) {
keepAsking = false;
} else {
myArray.add(userInput);
}
}
printShortestString(myArray);
System.out.printf("\n\nGOODBYE!\n");
keyboard.close();
}
public static void printShortestString(ArrayList<String> myArray) {
int index;
int index1 = 1;
for (index = 0; index < myArray.get(index).length(); index++) {
if (myArray.get(index).length() < myArray.get(index1).length()) {
System.out.printf("\nShortest string is \"%s\" with length %d",
myArray.get(index), myArray.get(index).length());
} else {
index1++;
}
}
return;
}
}发布于 2014-04-03 04:27:57
尝试对第40行使用for (index = 0; index < myArray.length(); index++) {。您在元素index中使用字符串的长度,而不是ArrayList的长度。
发布于 2014-04-03 04:30:39
你的方法似乎有问题。
public static void printShortestString(ArrayList<String> myArray) {
if (myArray.isEmpty()) return;
int len = myArray.get(0).length();
int shortestIndex = 0;
for (int index = 1; index < myArray.size(); index++) {
if (myArray.get(index).length() < myArray.get(index - 1).length()) {
len = myArray.get(index).length();
shortestIndex = index;
}
}
System.out.printf("\nShortest string is \"%s\" with length %d",
myArray.get(shortestIndex), len);
return;
}发布于 2014-04-03 04:28:32
我们需要查看printShortestString()的源代码,但我敢打赌,当索引i比数组的长度小一(而不是等于数组的长度)时,您需要将for循环更改为中断:
for {i=0; i < myArray.length(); i++) {
...
}https://stackoverflow.com/questions/22822204
复制相似问题