我试图让用户输入一个由 12 个数字组成的字符串,并将每个数字分配到数组空间中,尽管我能够将数字分配到数组中,但我在第 12 行遇到了越界异常,我不明白为什么。非常感谢您的帮助。 :)
import java.util.Scanner;
public class Practice
{
public static void main(String[] args)
{
char [] space = new char[13];
Scanner scanner = new Scanner(System.in);
System.out.println("Enter number ");
String input = scanner.nextLine();
for (int i = 0;i<space.length;i++)
{
char bCode = input.charAt(i);
space[i] = bCode; //assign bCode to store in space array
System.out.println((i+1)+"th " + space[i]);
}
最佳答案
最可能的问题是字符串input
长度不是13个字符,这意味着索引12超出范围,从而引发java.lang.StringIndexOutOfBoundsException
。在使用 charAt(i)
之前尝试检查输入的长度,例如
for (int i = 0; i < space.length; i++) {
if (input.length() > i) {
char bCode = input.charAt(i);
}
space[i] = bCode; //assign bCode to store in space array
System.out.println((i+1)+"th " + space[i]);
}
或者,您可以使用这个:
for (int i = 0; i < input.length(); i++) {
char bCode = input.charAt(i);
space[i] = bCode; //assign bCode to store in space array
System.out.println((i+1)+"th " + space[i]);
}
关于java.lang.StringIndexOutOfBoundsException : String index out of range: 12 in java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21950476/