gpt4 book ai didi

java.lang.IndexOutOfBoundsException : Index: 3, 大小:3

转载 作者:行者123 更新时间:2023-11-29 05:25:25 29 4
gpt4 key购买 nike

我不断得到

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;
}
}

最佳答案

尝试使用 for (index = 0; index < myArray.length(); index++) {对于第 40 行。您在元素 index 处使用字符串的长度,而不是 ArrayList 的长度。

关于java.lang.IndexOutOfBoundsException : Index: 3, 大小:3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22822204/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com