JAVA MAGIC SQUARE

Posts 13 of 3 · Page 1 of 1
JAVA MAGIC SQUARE
Guys can you help me out with these? i use JAVA language

i want to make a magic square that the initial value would be 1, the 1 should always be at the 1st row and middle column and it should be look like this it only accepts odd numbers. This is an activity so we should not ask our prof about this >.<

Input size of magic square:2
Invalid. Size should be odd

Input size again: 3

6 1 8
7 5 3
2 9 4

i tried to search in Google but can't find anything that'll match what I'm searching for. Please help me out with these. Thanks!!! and more power to us
Dude, you're doing it wrong. The numbers on a phone go like this:
The program asks for a number and keeps asking for a number until the number is odd.
After which the program creates the first line with random numbers with the middle one being a 1
and all of the other numbers are randomly selected.
HF.

Code:
import java.util.*;

public class MagicSquare 
{
	
	
	public static void main(String[]args)
	{
		String magicSquare = "";
		int size;
		int[] arrayNumbers = {2,3,4,5,6,7,8,9};
		Random randomNumber = new Random();
		Scanner input = new Scanner(System.in);
		
		do
		{
		System.out.printf("Enter an odd number: ");
		size = input.nextInt();
		}while(size < 0 && (size%2)==0);
		
		System.out.printf("Creating a magic square with the size of %d\n", size);
		
		//create first line before the 1
		for(int i = 0;i<size/2;i++)
		{
			magicSquare += arrayNumbers[randomNumber.nextInt(arrayNumbers.length)];
		}
		
			magicSquare += "1"; 
			
		for(int i = 0;i<size/2; i++)
		{
			magicSquare += arrayNumbers[randomNumber.nextInt(arrayNumbers.length)];
		}
			magicSquare += "\n";
			
		//first line created
			
			
		//create the rest of the lines
			for(int i = 0; i < size-1;i++)
			{
				for(int j = 0;j<size;j++)
				{
					magicSquare += arrayNumbers[randomNumber.nextInt(arrayNumbers.length)];
				}
				magicSquare += "\n";
			}
				
			System.out.printf("The magic square has been completed:\n%s",magicSquare);
	}	
}
Posts 13 of 3 · Page 1 of 1

Post a Reply

Similar Threads

Tags for this Thread

None

Need help?