【问题标题】:java.lang.StringIndexOutOfBoundsException: String index out of range: 12 in javajava.lang.StringIndexOutOfBoundsException:字符串索引超出范围:Java 中的 12
【发布时间】:2014-03-23 21:57:15
【问题描述】:

我试图让用户输入一个由 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]);

        }

【问题讨论】:

  • 感谢南比和亚当。您的解决方案是正确的。非常感谢。
  • @user3339860 谢谢 如果有帮助请接受我的回答

标签: java bluej


【解决方案1】:

您在打印输入值时检查space 可变长度

检查input.length() 长度而不是space.length 长度,这就是你得到StringIndexOutOfBoundsException 的原因

改一下

 here -> for (int i = 0;i<space.length;i++) 
            {

到这里

for (int i = 0;i<input.length();i++) 
        {

【讨论】:

    【解决方案2】:

    最可能的问题是字符串 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]);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-03-02
      • 1970-01-01
      • 2016-02-25
      • 2018-11-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-14
      相关资源
      最近更新 更多