Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package prog4;
- import java.util.Scanner;
- import java.util.Random;
- public class Prog4 {
- public static void main(String[] args) {
- int sum, order; //Sum that the square should add up to and
- //order is number of rows and columns
- Scanner scan = new Scanner(System.in);
- System.out.println("\t-MAGIC SQUARE GENERATOR-");
- System.out.print("Enter the sum: ");
- sum = scan.nextInt();
- System.out.print("Enter the order of the square: ");
- order = scan.nextInt();
- int[] square = new int[2*order];
- square = magicSquare(sum, order);
- int[][] fullSquare = new int[order][order];
- for(int y=0;y<order;y++)
- {
- for(int x=0;x<order;x++)
- {
- fullSquare[y][x]=square[order+y-1]+square[x];
- System.out.printf("%3d ", fullSquare[y][x]);
- }
- System.out.println();
- }
- }
- public static int[] magicSquare(int sum, int order){
- int i, arraySum=0; //counter variable and arraySum to keep track
- //of total sum of array values
- int[] squareArray = new int[2*order]; //declare array for numbers
- Random rand = new Random(); //Create random number generator
- //Populate array with random integers:
- for(i=0; i<(2*order-1); i++)
- {
- squareArray[i] = rand.nextInt(sum/(2*order)+1);
- arraySum+=squareArray[i];
- }
- //Make sure the last value of the array insures the sum is equal to
- //to the sum specified:
- squareArray[i] = sum-arraySum;
- return squareArray;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement