我一直在
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;
}
}
答案 0 :(得分:2)
尝试将for (index = 0; index < myArray.length(); index++) {
用于第40行。您使用元素index
处字符串的长度,而不是ArrayList的长度。
答案 1 :(得分:1)
你的方法似乎有问题。
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;
}
答案 2 :(得分:0)
我们需要查看printShortestString()
的来源,但我敢打赌,当索引i
小于1时,您需要更改for循环。数组的长度,而不是等于数组的长度:
for {i=0; i < myArray.length(); i++) {
...
}
答案 3 :(得分:0)
此行导致您退出索引:
for (index = 0; index < myArray.get(index).length(); index++)
您希望迭代数组的大小:
for (index = 0; index < myArray.size(); index++)
答案 4 :(得分:0)
printShortestString(...)
背后的逻辑不正确。您希望遍历列表大小(而不是字符串大小)。这里发生的事情是:
myArray .get(index) .length()
list object at a given index of this list size of that object
你想要的是:
myArray .size()
list size of list
变化:
for (index = 0; index < myArray.get(index).length(); index++) {
要:
for (index = 0; index < myArray.size(); index++) {
答案 5 :(得分:0)
String word = null;
for (index = 0; index < myArray.size(); index++) {
if (word == null) {
word = myArray.get(index);
continue;
}
if (myArray.get(index).length() < word.length()) {
word = myArray.get(index).length()
}
}
System.out.println("The shortest word is:" + word );