Posted By

DrPepper on 01/28/11


Tagged


Versions (?)

[JAVA] CH7 2-Dimensional Array


 / Published in: Java
 

  1. import java.util.Scanner;
  2.  
  3. public class MagicSquares
  4. {
  5. public static int userInput;
  6. private static int g,c;
  7. public int[][] matrix;
  8. private int ROW = 3;
  9. private int COLUMNS = 3;
  10. private int x,z,m,a,b,d;
  11. private int sumHolizontal;
  12. private int sumVertical;
  13. private int sumCross;
  14. public static boolean booleanVar;
  15. public MagicSquares()
  16. {
  17. matrix = new int [ROW][COLUMNS];
  18. userInput = 0;
  19. m=1; a=0; b=0; c=0; d=1;
  20.  
  21. }
  22.  
  23. public static int getUserInput()
  24. {
  25. System.out.println("Enter a number : ");
  26. Scanner sc = new Scanner(System.in);
  27. return sc.nextInt();
  28. }
  29. public void add(int i)
  30. {
  31. matrix[z][x] = i;
  32. ++x;
  33. if(x == 3)
  34. { z++; x=0; }
  35. m++;
  36. }
  37.  
  38. public void printData()
  39. {
  40. if(d==3)
  41. { System.out.println(" "+matrix[a][b]); }
  42. else
  43. { System.out.print(" "+matrix[a][b]); }
  44. ++b;
  45. if(b == 3)
  46. { a++; b=0; d=0; }
  47. d++;
  48. }
  49.  
  50. public boolean isMagic()
  51. {
  52. sumHolizontal = matrix[0][0] + matrix[0][1] + matrix[0][2];
  53. sumVertical = matrix[0][0] + matrix[1][0] + matrix[2][0];
  54. sumCross = matrix[0][0] + matrix[1][1] + matrix[2][2];
  55. return sumHolizontal == sumVertical;
  56. }
  57.  
  58. public static void main(String[] args)
  59. {
  60. MagicSquares ms = new MagicSquares();
  61. for(g = 0; g< 9; g++)
  62. {
  63. userInput = getUserInput();
  64. ms.add(userInput);
  65. }
  66.  
  67. /**
  68.   using a for loop print number
  69.   */
  70. System.out.println();
  71. System.out.println("*** Algolism list ***");
  72. for(c = 0; c<9;c++)
  73. { ms.printData(); }
  74. /**
  75.   check bool
  76.   */
  77. booleanVar = ms.isMagic();
  78. System.out.println("This is a Magic Squares : "+booleanVar);
  79. }
  80. }

Report this snippet  

You need to login to post a comment.