2b

Advanced Placement

Computer Science Lab

 

 

Data Types and Operators  & a Magic Square

 

Introduction

 

In this lab we will continue to explore the Java primitive types and operators.  In the programming exercise you will combine elements for the various exercises that we have done so far to make a program that actually does something—in this case make what is known in mathematics as a magic square

 

 

 

 

 

 

Programming Assignment

 

 

 

Write a program to produce a magic square.  In a magic square, the sum of each row, column and diagonal is equal.  For example the following is a magic square in which the sum is three:

 

–3

2

3

6

1

–4

–1

0

4

 

The secret of the magic square is this: for any values of x, y, and z, a magic square can be formed on the basis of the following:

 

 

x–z

x+z–y

x+y

x+y+z

x

x–y–z

x–y

x+y–z

x+z

 

In the above example, x = 1, y = 2, and z = 3 produces a magic square whose sum is three.  Your program should prompt the user for the values x, y, z, produce the magic square and then print out the sum.  You should make a new project with the Keyboard package and import Keyboard into your magic square source code.  Turn in a program listing your magic square source code.  Source code should use proper formatting and be fully commented.  Also turn in a copy of your output.  This can be obtained by running the program and then using AltPrintScreen to copy the window of the output onto the clipboard.  Prior to using the Alt-Print Screen, change the background of the window to white and the text to black.  This can be done by clicking on the icon in the upper left hand corner of the output window and going to the properties item in the menu that appears. In the dialog box that appears just change background to white and text or foreground to black.  Then paste the contents of the clipboard into WordPad and print out the document.  In addition to the source code, the output, also turn in the answer to the questions listed below.