【问题标题】:Why am I getting StringIndexOutOfBoundsExceptiuon when I copy and paste input?为什么我在复制和粘贴输入时收到 StringIndexOutOfBoundsExceptiuon?
【发布时间】:2020-09-07 04:07:54
【问题描述】:

我确保缓冲区完全为空(即没有换行符)。仅当我手动输入时才有效。

如果我复制并粘贴输入,我必须按一个额外的“Enter”,这可能是导致异常的罪魁祸首:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0

我的问题本质上是:为什么只有在我复制和粘贴输入时才会发生这种情况以及如何纠正它?

public class Skener {

public static void main(String[] args) 
{
    //Creating scanner and associated input variables
    Scanner scan= new Scanner(System.in);
    int r,zr,c,zc;
    
    
    //Reading input variables
    r=scan.nextInt();
    c=scan.nextInt();
    zr=scan.nextInt();
    zc=scan.nextInt();
    
    scan.nextLine();//cleaning up buffer
    
    
    char[][] matrix= {};
    
    matrix=read2DArray(r, c, matrix); <--Error happens in this method
    .....
}

public static char[][] read2DArray(int r,int c,char[][] twoD_array)
{
    Scanner scan= new Scanner(System.in);
    
    int row,col;
    String input;
    twoD_array=new char[r][c];
    
    for(row=0;row<=r-1;row++)
    {   
        input=scan.nextLine();
        for(col=0;col<=c-1;col++)
        {
        
            twoD_array[row][col]=input.charAt(col); <-- Error occurs at this line
        }
    
    }
    
    return twoD_array;
}

这是一个示例输入:

3 3 1 2
.x.
x.x
.x.

及对应的样本输出:

..xx..
xx..xx
..xx..

编辑:

像上面给出的示例输入这样的输入崩溃。 崩溃时col 的值为 0。

【问题讨论】:

  • 异常发生时input的值是多少?异常发生时col的值是多少?
  • 任何适当的输入都会发生异常。示例输入在我复制和粘贴时也给了我异常
  • 你必须调试和检查。
  • 复制的时候不是复制\nchar。异常发生时调试并检查input的值。
  • 我认为col 的值为0。这里有1 个可能的输入:3 3 1 2 .x. x.x .x.(参考上面的示例输入,它在评论中没有正确显示)

标签: java string indexoutofboundsexception


【解决方案1】:

因为你复制了多余的字符而你没有注意到

见:

when you copy the image notice the extra characters

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-05
    • 2022-08-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多