Concept explainers
QUESTION: Creating a JAVA program which should implement a method that verifies whether a given 4 x 4 square (containing 16 values) is a Magic Square with a given magicValue. Also, adding code to generate values for a Magic Square based on a magicValue.
The code here is good to solve for verifying if it is a magic square but not n generating a new Magic Square, it is not as in the picture. The sum in row and columns are not equal.
PLEASE, PLEASE, PLEASE, don't post code from anywhere else. Please help me by working on this code here.
import java.util.*;
import java.awt.*;
public class MagicSquare{
static int checkMag(int mat[][],int M)
{
// Function for checking Magic square
int i, j,n=4; int sum=0; // filling matrix with its count value // starting from 1;
for ( i = 0; i < n; i++) {
for ( j = 0; j < n; j++)
sum=sum+mat[i][j];
if(sum!=M)
{
return 0;
}
sum=0;
}
for ( i = 0; i < n; i++) {
for ( j = 0; j < n; j++)
sum=sum+mat[j][i];
if(sum!=M)
{
return 0;
}
sum=0;
}
int sumR=0,
sumL=0;
for ( i = 0; i < n; i++) {
for ( j = 0; j < n; j++) {
if(i==j) sumL=sumL+mat[i][j];
if((i+j)==(n-1))
sumR=sumR+mat[i][j]; } }
if(sumR!=M )
{
return 0;
}
if(sumL!=M)
{
return 0;
}
return 1;
}
static int[][] builtMagic(int mat[][],int M,int Mnew) {
int i,j,n=4;
Mnew=Mnew-M;
int rem=Mnew%4;
int quo =Mnew/4;
if(rem==0){ for ( i = 0; i < n; i++) {
for ( j = 0; j < n; j++)
mat[i][j] =mat[i][j]+quo; }}
else{
for ( i = 0; i < n; i++) {
for ( j = 0; j < n; j++) {
mat[i][j] =mat[i][j]+quo;
if(mat[i][j]==13||mat[i][j]==14||mat[i][j]==15||mat[i][j]==16) {
mat[i][j] =mat[i][j]+rem;
}
}
}
}
return mat;
}
public static void main (String[] args) {
//Scanner object
Scanner sc = new Scanner(System.in);
DrawingPanel panel = new DrawingPanel(500, 500);
Graphics g = panel.getGraphics();
// creating a 2d array of magic square numbers
int numbers[][] = { { 8, 11, 14, 1 }, { 13, 2, 7, 12 }, { 3, 16, 9, 6 }, { 10, 5, 4, 15 } };
// drawing grid of cell width = 80 centered at panel center
drawGrid(g, panel.getWidth() / 2, panel.getHeight() / 2,numbers.length, 80);
//drawNumbers(g, panel.getWidth() / 2, panel.getHeight() / 2, 80, numbers);
// drawing title string centered at y=50
drawString(g, "CSC 142 Magic Square", panel.getWidth() / 2, 50);
int n = 4;
int magMat[][]= new int[n][n];
int M;
int baseMat[][]={{12,6,15,1},{13,3,10,8},{2,16,5,11},{7,9,4,14}};
for (int k=0;k<10;k++){
System.out.println("Enter magic value");
M=sc.nextInt();
System.out.println( "Enter " + ( n*n ) + " values" );
for(int i=0;i<n;i++) {
for(int j=0;j<n;j++)
{
magMat[i][j]= sc.nextInt();
}
}
if(checkMag(magMat,M)==1) {
System.out.println("It is a magic square");
panel.clear();
makeMagicSquareGrid(panel,magMat,k+1); // insert magic m=numbers on grid
}
else {
System.out.println("It is not a magic square"); }
System.out.println("Enter another magic value greater than 34");
int Mnew=sc.nextInt();
magMat=builtMagic(magMat,34,Mnew);
panel.clear();
makeMagicSquareGrid(panel,magMat,k+1); // insert magic m=numbers on grid
}
}
static void makeMagicSquareGrid(DrawingPanel dp,int[][] magMat, int k){
Graphics g = dp.getGraphics();
drawGrid(g, dp.getWidth() / 2, dp.getHeight() / 2,magMat.length, 80);
// drawing numbers
drawNumbers(g, dp.getWidth() / 2, dp.getHeight() / 2, 80, magMat);
// drawing title string centered at y=50
drawString(g, "Magic Square "+k, dp.getWidth() / 2, 50);
String filename="MagicMatrix"+k+".jpeg";
try{
dp.save(filename);
}
catch(Exception e)
{
System.out.println("File coudn't be saved");
}
}
public static void drawGrid(Graphics g, int centerX, int centerY, int row, int cell) { // cell width
int x = centerX - (row / 2) * cell;
int y = centerY - (row / 2) * cell;
// setting black color
g.setColor(Color.BLACK);
// looping for each row and column
for (int i = 0; i < row; i++) {
for (int j = 0; j < row; j++) {
// drawing a square with equal sides
g.drawRect(x + (cell * j), y + (cell * i),cell, cell);
}
}
}
// method to draw the numbers (given in a 2d array) inside a grid (assuming
// grid is previously drawn)
public static void drawNumbers(Graphics g, int centerX, int centerY,int cell, int numbers[][]) {
int x = centerX - (numbers.length / 2) * cell;
int y = centerY - (numbers.length / 2) * cell; //Setting red color
g.setColor(Color.RED); // Customizing font
g.setFont(new Font("Georgia", Font.BOLD, 25));
for (int i = 0; i < numbers.length; i++) {
for (int j = 0; j < numbers.length; j++) {
// Setting center cell
int xx = x + (cell * j) + cell / 2;
int yy = y + (cell * i) + cell / 2;
// Setting center text
drawString(g, String.valueOf(numbers[i][j]), xx, yy);
}
}
} public static void drawString(Graphics g, String text, int centerX, int centerY) {
// getting FontMetrics of current font
FontMetrics metrics = g.getFontMetrics(g.getFont());
// finding width of text in pixels using metrics
int width = metrics.stringWidth(text);
// drawing string center aligned
g.drawString(text, centerX - width / 2, centerY + metrics.getHeight()/ 2);
}
}
Trending nowThis is a popular solution!
Step by stepSolved in 2 steps
- Need help with following Java method: import java.util.Scanner; import java.lang.Math; public class CosineFromScratch { /* The following code demonstrates how to estimate the cosine of a number. Your assignment is to migrate the calculation of the cosine into a new static method named cosine. The method should take one double input and return one double output. Make sure to call the method from main and set the variable estimate equal to the returned value. */ public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("\nGive me a number: "); double x = input.nextDouble(); //Trying to find cosine of this number double correct_cos = Math.cos(x); //START HERE: The following code goes into //the method. //Source for the following: //https://austinhenley.com/blog/cosine.html double num_terms = 10; int div = (int)(x / Math.PI); x = x - (div * Math.PI); int sign = -1; double estimate = 1.0;…arrow_forwardUse java and correctly indent code.arrow_forwardNeeds to be written in java: Write a program with a main() method that asks the user to input an integer array of 10 elements.Next, create three methods described below. From inside your main() method, call each of thethree methods described below and print out the results of the methods 2, 3, which return values.1. printReverse() - a method that receives an array of integers, then reverses the elements ofthe array and prints out all the elements from inside the method. Print all in one lineseparated by commas (see sample output below).2. getLargest() – a method that receives an array of integers, then returns the largest integervalue in the array. (print result from main())3. computeTwice()- a method that receives the previously reversed array of integers, thenreturns an array of integers which doubles the value of each number in the array (see thesample output below). (print result from main())Sample output:Enter a number:22Enter a number:34Enter a number:21Enter a number:35Enter a…arrow_forward
- Needs to be written in java and completed using "for loops" or "nested for loops" and in one program just seperate methods: Write a program that calls these three methods. method 1 should print: 5 4 3 2 1 4 3 2 1 3 2 1 2 1 1 method 2 should print: 1 2 3 4 5 1 2 3 4 1 2 3 1 2 1 method 3 should create and array and store 10 multiples of 5 and print it out. Use for loop to generate the multiples and then print them out using a second for loop.arrow_forwardWrite a method called drawDiamond() that outputs lines of '*' to form a Diamond with equal length diagonals. Method drawDiamond() has one parameter, an integer representing the diagonal of the diamond. Assume the diagonal length is always odd and less than 20. Output 9 spaces before the first '*' on the first line for correct formatting. Either drawTriangle or at least one of its helper methods must be recursive. Ex: If the input of the program is: 3 the method drawDiamond() outputs: * *** * Ex: If the input of the program is: 15 the method drawDiamond() outputs: * *** ***** ******* ********* *********** ************ *************** ************* *********** ********* ******* ***** *** * Note: the diamond is made up of a rightside up triangle and an upside down triangle. import java.util.Scanner; public class LabProgram { /* TODO: Write drawDiamond() method here. */ /* You can add other helper methods if needed…arrow_forwardchange Summation Integers problem to Finding the minimumproblem. Make sure you properly wrote/updated all text messages, method names,and math calculations.Hint: You can use java.lang.Math.min() method.Example: System.out.printf("The min of the integers %4d and %4d and %4dis %7d\n", a, b, c, MinTest(a, b, c));arrow_forward
- change Summation Integers problem to Finding the minimumproblem. Make sure you properly wrote/updated all text messages, method names,and math calculations.Hint: You can use java.lang.Math.min() method.Example: System.out.printf("The min of the integers %4d and %4d and %4dis %7d\n", a, b, c,d MinTest(a, b, c,d)); fix below code structurearrow_forwardWrite a Java program that expands a given binomial (x + y)^n, where integer n is user input. To do the work of the binomial expression, first create a method that accepts n as a parameter and then returns an array holding the coefficients needed for the binomial expansion using the Pascal’s Triangle method. Create a 2nd method which takes the array holding the coefficients as a parameter and prints the appropriate binomial expansion. For example, if n = 5 is entered by the user, the method calculating the coefficients should return {1,5,10,10,5,1} and the method that prints the expansion should print the following: (x + y)^5 = x^5 + 5x^4y + 10x^3y^2 + 10x^2y^3 + 5xy^4 + y^5 Your main method should use an appropriate loop for repeated inputs and automatically call the methods to calculate the coefficients and print the binomial expansion. There isn’t a need for a menu although you should ask the user if they want to quit or continue after their binomial expansion is printed each time.…arrow_forward
- Database System ConceptsComputer ScienceISBN:9780078022159Author:Abraham Silberschatz Professor, Henry F. Korth, S. SudarshanPublisher:McGraw-Hill EducationStarting Out with Python (4th Edition)Computer ScienceISBN:9780134444321Author:Tony GaddisPublisher:PEARSONDigital Fundamentals (11th Edition)Computer ScienceISBN:9780132737968Author:Thomas L. FloydPublisher:PEARSON
- C How to Program (8th Edition)Computer ScienceISBN:9780133976892Author:Paul J. Deitel, Harvey DeitelPublisher:PEARSONDatabase Systems: Design, Implementation, & Manag...Computer ScienceISBN:9781337627900Author:Carlos Coronel, Steven MorrisPublisher:Cengage LearningProgrammable Logic ControllersComputer ScienceISBN:9780073373843Author:Frank D. PetruzellaPublisher:McGraw-Hill Education