2015-11-25 3 views
1

почему-то эта вещь выходит за пределы, если n не объявлена ​​выше, например, если n=3;, то нет никаких проблем, но если я опираюсь на пользовательский ввод для значения n она выходит за пределы.Магический Квадрат функции с использованием Java

import java.io.*; 
public class MagicSquare_Cubz { 
BufferedReader in = new BufferedReader (new InputStreamReader(System.in)); 

int n; 
int [][] array; // = new int [z][z]; 
int i=0; 
int j = n/2; 
int k = 1; 

    public static void main(String args[]) throws IOException{ 
     new MagicSquare_Cubz(); 
    } 


    public MagicSquare_Cubz() throws IOException { 
     System.out.print("MAGIC SQUARE\n"); 
     System.out.print("============\n"); 
     System.out.print("Enter a number: "); 

     n=Integer.parseInt(in.readLine()); 
     //n=o; 
     array = new int [n][n]; 
     //problem.. for some reason the array goes out of bounds if n is not declared... 
     disp(); 

      if(n%2!=0){ 
       exe(); 
       disp(); 
      } 

      else{ 
       System.out.print("Enter odd numbers only"); 
      } 

    } 

    public void exe() throws IOException{ 

    System.out.println("IT WORKS " + n); 

     while(k<=n*n){ 

      array[i][j] = k++; 
      i--; // Making one step upward 
      j++; // Moving one step to the right 
       if(i<0 && j>n-1){ // Condition for the top-right corner element 
        i = i+2; 
        j--; 
       }  
       if(i<0) // Wrapping around the row if it goes out of boundary 
        i = n-1; 

       if(j>n-1) // Wrapping around the column if it goes out of boundary 
        j = 0; 

       if(array[i][j]>0){ // Condition when the cell is already filled 
        i = i+2; 
        j--; 
       }  
     }    

    } 

    public void disp() throws IOException{ 

     for(int x=0 ; x<n ; x++){ 
      for(int y=0 ; y<n ; y++){ 
       System.out.print(array[x][y]+ " "); 
      } 
      System.out.println(""); 

     } 
    } 


} 
+0

Пожалуйста, добавьте вашу трассировку стека – Ramanlfc

+0

Похоже, что int j = n/2; без n, имеющего ценность, может быть что-то, что нужно изучить. Не знаете, почему вы ожидаете не объявлять n. Если вы хотите использовать n, я ожидаю, что объявление будет необходимо ... –

ответ

0

Добавить

j = n/2; 

после

n=Integer.parseInt(in.readLine()); 
0

просто объявить J в главном классе т.е. Int J; затем инициализируйте его, если блок.

if(n%2!=0){ 
         j = n/2; 
        exe(); 
        disp(); 
       } 
Смежные вопросы