【问题标题】:Exception thrown with taking a two dimentional array input. I'm getting an unexpected exception but my code looks okay使用二维数组输入引发异常。我遇到了意外的异常,但我的代码看起来还不错
【发布时间】:2017-04-24 05:51:15
【问题描述】:

在将两行作为 3X3 矩阵 (n=3) 的输入后,我得到了 ArrayIndexOutofBound 异常。一旦我将第 6 个整数作为输入,即完成我的第二行,它就会引发异常。

int i, j;
System.out.println("Enter number of rows and columns");
Scanner s = new Scanner(System.in);
int n = s.nextInt();
int[][] a = new int[n][n];
for(i = 0; i < n; i++)
{
    for(j = 0; i < n; j++)
    {
        a[i][j] = s.nextInt();
    }
}
s.close();

【问题讨论】:

  • 错字:for(j=0;i&lt;n;j++){ -> for(j=0;j&lt;n;j++){
  • 大声笑。谢谢你:)

标签: java arrays exception


【解决方案1】:

您在j 循环中犯了一个简单的错字:

int i,j;
System.out.println("Enter number of rows and columns");
Scanner s=new Scanner(System.in);
int n=s.nextInt();
int[][] a=new int[n][n];
for(i=0;i<n;i++){
 for(j=0;j<n;j++){  // This line had a typo.
    a[i][j]=s.nextInt();
 }
}
s.close();

【讨论】:

    【解决方案2】:

    第二个 for 循环有错字,尝试使用 try-with-resources 自动关闭流。

        int i, j;
        System.out.println("Enter number of rows and columns");
        try (Scanner s = new Scanner(System.in)) {
            int n = s.nextInt();
            int[][] a = new int[n][n];
            for (i = 0; i < n; i++) {
                for (j = 0; j < n; j++) {
                    a[i][j] = s.nextInt();
                }
            }
        } catch (InputMismatchException e) {
            e.printStackTrace();
        }
    

    【讨论】:

    • 谢谢。但是,如果我使用上面的代码,我不会收到异常,但是由于拼写错误,我的代码仍然无法运行,并且 catch 块将处理我的异常。我在这里吗?如果我在这里,如果我的代码仍然不起作用,那么 try-catch 块有什么用?
    • 您需要在所有情况下修正错字。使用 try/cacth 将帮助您捕捉应用程序的意外失败/行为 例如,您可以向用户显示正确的错误消息,这样他就不会在看到意外行为后感到困惑。对资源使用 try 将改进您的代码。例如。如果你在没有 try catch 的情况下得到一个异常,比如说 InputMismatchException,即使你的代码中有scanner.close(),你的 Scanner 也会保持打开状态,但是如果你使用 try-with-resources 资源,它实现了 AutoCloseable 接口(Scanner 是一个其中),将在出现错误(异常)时关闭。
    猜你喜欢
    • 1970-01-01
    • 2020-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多