Spiral-shaped matrix

0

I try to make a spiral-shaped matrix, but when I execute it in cmd I get an error that I could not correct.

I enclose the error and the code respectively.

  

exception in thread main java.lang.ArrayIndexOutOfBoundsException:   -2147483648            at caracolfinal.main (caracolfinal.java:29)

import java.util.Scanner;
public class caracolfinal{
    public static void main(String args[]){


Scanner tcl=new Scanner(System.in);

int n=0;
int inicio=0;
int lim= n-1;
int cont=1;


System.out.println(" Ingrese el valor para N ");

n =tcl.nextInt();

    int [][] matriz = new int[n][n];

    while(cont<= (n*n))
    {
        for(int i=inicio;i<=lim;i++)
        {
            matriz[inicio][i]=cont++;

        }
        for(int i=inicio+1;i<=lim;i++)
        {
            matriz[i][lim]=cont++;
        }
        for(int i=lim-1;i>=inicio;i--)
        {
            matriz[lim][i]=cont++;
        }
        for(int i=lim-1;i>=inicio+1;i--)
        {

            matriz[i][inicio]=cont++;

        }
        inicio++;
        lim--;

    }
    for(int j=0;j<=matriz.length;j++){
        System.out.println();

        for(int i=0;i<=matriz.length;i++){
            System.out.print(matriz[i][j]+"\t");
    }

    }   

    }
}
    
asked by D1998 20.12.2017 в 05:53
source

1 answer

0

The variable n initializes it to zero, lim is -1, now, the aggravating factor is that lim remains with that -1 and not with the value registered by keyboard minus 1.

What I want to go to is that you update lim after capturing the dimension of the array by keyboard:

n = tcl.nextInt();
lim = n - 1;
    
answered by 20.12.2017 в 06:25