Java程序辅导

C C++ Java Python Processing编程在线培训 程序编写 软件开发 视频讲解

客服在线QQ:2653320439 微信:ittutor Email:itutor@qq.com
wx: cjtutor
QQ: 2653320439
 
 
 
 
 
 
 
 
 
 
 
 
 
Andrew Butcher 
 
abutcher@mix.wvu.edu 
Donald Adjeroh – Class Section 007 
Matt Williamson – Lab Section 010 
Project 3 – 11/15/06 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 1
Question 1 (Student Records) 
Chapter 7, Programming Exercise #14, pp. 441 
 
Program Specification 
Write a program that reads a student’s name together with his or her test scores.  The 
program should then compute the average test score for each student and assign the 
appropriate grade.  The grade scale is as follows: 90 – 100, A; 80 – 89, B; 70 – 79, C; 60 
– 69, D; 0 – 59, F. 
 
Your program should use the following methods: 
a. A void method, calculateAverage, to determine the average of the five test scores 
for each student.  Use a loop to read and sum the five test scores.  (This method 
does not output the average test score.  That task must be done in the method 
main.) 
b. A value returning method, calculateGrade, to determine and return each student’s 
grade. (This method does not output the grade.  That task must be done in the 
method main.) 
 
Analysis 
This program is expected to accept from a user, the input and output file names though 
the use of GUI dialog boxes.  It should then read from a text file multiple student names 
and their associated five test scores.  From there it will calculate the average for the given 
student as well as their associated letter grade. The program will output the name, test 
scores, and average to a text file.  
Program Inputs – Filenames and associated strings and integers from said files. 
Program Outputs – Student names, grades, averages, and associated grade letters. 
Formula or Relations 
Five test scores / 5 = individual average 
90 – 100, A; 80 – 89, B; 70 – 79, C; 60 – 69, D; 0 – 59, F 
 
Design 
Initial Algorithm 
1. Obtain input from user. 
2. Process input. 
3. Output results. 
Refinement 
1. Through a GUI dialog box – prompt the user to input the input file name and the 
output file name.  From files, extract names and test scores. 
2. Determines averages and associated grade letters for each student. 
3. Output to file will be student name, their test scores, their average, and associated 
grade letter, as well as the class average. 
 
Test Plan 
Testing the program will be very simple.  The only given errors will be a wrong file 
name, or illogical file data (in the wrong format.) 
 
 2
Algorithm Test 
Suppose within the input text file was written: 
Johnson 85 83 77 91 76 
Skywalker 92 86 99 83 91 
Kenobi 89 100 67 23 90 
The program would output: 
Name  Test1 Test2 Test3 Test4 Test5 Average Grade 
Johnson 85.00 83.00 77.00 91.00 76.00 82.40  B 
Skywalker  92.00 86.00 99.00 83.00 91.00 90.20  A 
Kenobi 89.00 100.00 67.00 23.00 90.00 73.80  C 
 
Implementation 
//----------------------------------------------------------------------------- 
//  testAverageIO.java 
//  This program. in a loop, reads a student's name and up to five test scores 
//  from a text file.  The program then averages those test scores and applies 
//  the associated grade letter.  Output is also to a file. 
//  Author: Andrew Butcher 
//  CS110 Section 007 
//  Lecturer: Don Adjeroh 
//  Lab Section: 010 
//  Lab Instructor: Matt Williamson 
//  Last Modified: 11/16/06 
//----------------------------------------------------------------------------- 
   import java.util.*; 
   import java.io.*; 
   import javax.swing.*; 
 
    public class testAverageIO 
   { 
  // Static variables 
      static double average, grade, sum; 
      static int count; 
      static double[] gradeArray; 
      static String outputfileName, inputfileName, name, gradeLetter, outputStr; 
    
       public static void main(String[] args) 
            throws FileNotFoundException 
      { 
   // Asking user for the input and output file names. 
         inputfileName = JOptionPane.showInputDialog("Please enter the name of the file 
you would like to open. (c:\\inputFile.txt)"); 
         outputfileName = JOptionPane.showInputDialog("Please enter hte name of the file 
you would like to output to. (c:\\outputFile.txt)"); 
         
// inFile and outFile objects. 
 3
PrintWriter outFile = new PrintWriter(outputfileName); 
         Scanner inFile = new Scanner(new FileReader(inputfileName)); 
    
       // Printing the column headers in the output text file. 
         outFile.printf("%8s %8s %8s %8s %8s %8s %8s %8s %n", "Student", "Test1", 
"Test2", "Test3", "Test4", "Test5", "Average", "Grade"); 
         double[] gradeArray = new double[5]; 
 
         while (inFile.hasNext()) 
  // While loop reads input from a file 
  // as long as there is information to read. 
         { 
            name = inFile.next(); // Gets the name of the student 
           
            sum = 0; 
            count = 0; 
           
            while (count != 5) 
  // While loop creates the test score array 
  // and also the sum of grades for a single student.  
            { 
               grade = inFile.nextDouble(); 
               gradeArray[count] = grade; 
               sum = sum + grade; 
               count++; 
            }    
            calculateAverage(); 
  // Prints a single student's information before continuing to loop. 
           outFile.printf("%8s %8.2f %8.2f %8.2f %8.2f %8.2f %8.2f %8s %n", name, 
gradeArray[0], gradeArray[1], gradeArray[2], gradeArray[3], gradeArray[4], average, 
calculateGrade(average)); 
         } 
         inFile.close(); 
         outFile.close(); 
       
      } 
       public static void calculateAverage() 
       // Divides the sum by 5, which is the count 
      // to arrive at the average. 
      { 
         if (count != 0) 
         { 
            average = sum / count; 
         } 
         else 
         { 
 4
            average = 0; 
         } 
      } 
    
       public static String calculateGrade(double average) 
          // calculateGrade() method determines the grade letter 
          // to be attributed with the average. 
      { 
         String gradeLetter = ""; 
         if (average >= 90 && average <= 100) 
         { 
            gradeLetter = "A"; 
         } 
         else if (average >= 80 && average <= 89) 
         { 
            gradeLetter = "B"; 
         } 
         else if (average >= 70 && average <= 79) 
         { 
            gradeLetter = "C"; 
         } 
         else if (average >= 60 && average <= 69) 
         { 
            gradeLetter = "D"; 
         } 
         else if (average >= 0 && average <= 59) 
         { 
            gradeLetter = "F"; 
         } 
   return gradeLetter; 
      }// ... End of calculateGrade() 
     
   }// ... End of testAverageIO() 
 
Test Results 
The test aforementioned in Algorithm test went according to plans.  Also a custom 
FileNotFoundException error message was created to inform the user of invalid input 
files. 
  
  
 
 
 
 
 
 
 5
Question 2 
(A) Chapter 6, Programming Exercise # 1, pp. 356 
 
Program Specification 
Design a GUI program to find the weighted average of four test scores.   The user is 
supposed to enter the data and press a Calculate button.  The program must display the 
weighted average.  
 
Analysis 
This program is expected to create a GUI pane that accepts four test scores and their 
associated weights.  The pane will contain buttons for calculated the weighted average, 
exiting the program, and clearing the cells to calculate another average. 
 
Program Inputs – Four test scores and their associated weights. 
Program Outputs – Weighted average. 
Formula or Relations 
Average = test1 * weight1 + test2 * weight2 + test3 * weight3 + test4 * weight4 
 
Design 
 Initial Algorithm 
1. Generate GUI pane. 
2. Read input from the user. 
3. Process input from user. 
4. Output the weighted average. 
Refined Algorithm 
1. Generate GUI pane. 
2. Read input from text fields. 
3. Process input from user. 
i. Average = test1 * weight1 + test2 * weight2 + test3 * weight3 + test4 
* weight4 
4. Output weights average to text field. 
 
Methods 
 
Method testAverageGUI( ) 
 This method sets all button, label, and textfield objects and sets their position in 
the content pane as well as setting the size, visibility, and default close operation.  
 
Class CalculateButtonHandler( ) 
 This class listens for an event to occur on the calculate button.  Once the button is 
invoked, it tells the program what to do with the input to arrive at and display the 
weighted average.  
 
Class ClearButtonHandler( ) 
 This class listens for an event to occur on the clear button.  Once the button is 
invoked, it tells the program to clear all cells.  
 6
Class ExitButtonHandler( ) 
 This class listens for an event to occur on the exit button.  Once the button is 
invoked, it tells the program to close. 
 
Test Plan 
All errors will result from faulty input.  The program will only accept number values, int, 
double, or float, for test grades and double or float for test weights.  The program will 
round down on the weighted average. 
 
Algorithm Test 
Suppose the tests and weights input were: 
Test 1: 100 Weight 1:  .3 
Test 2: 90 Weight 2:  .4 
Test 3: 76 Weight 3:  .1 
Test 4: 92 Weight 4:  .2 
Weighted Average:  92.0 
 
Implementation 
//----------------------------------------------------------------------------- 
//  testAverageGUI.java 
//  This program is a GUI program with an interface.  It takes in four test scores 
//  along with their associated weights and outputs an average.  
//  Author: Andrew Butcher 
//  CS110 Section 007 
//  Lecturer: Don Adjeroh 
//  Lab Section: 010 
//  Lab Instructor: Matt Williamson 
//  Last Modified: 11/12/06 
//----------------------------------------------------------------------------- 
import javax.swing.*; 
import java.awt.*; 
import java.awt.event.*; 
 
public class testAverageGUI extends JFrame 
 { 
  // The height and width of the window. 
  private static final int WIDTH = 450; 
  private static final int HEIGHT = 300; 
   
  // Declaration of all JLabel, JTextField, and JButton objects. 
private JLabel score1L, score2L, score3L, score4L, weight1L, weight2L, weight3L, 
weight4L, averageL, blankL, blank2L, blank3L; 
private JTextField score1TF, score2TF, score3TF, score4TF,weight1TF, weight2TF, 
weight3TF, weight4TF, averageTF; 
private JButton exitB, calculateAverageB, clearB; 
   
 7
  private CalculateButtonHandler caHandler; 
  private ExitButtonHandler ebHandler; 
  private ClearButtonHandler clHandler; 
    
   
  public testAverageGUI() 
    // Sets all values on the pane. 
    // Sets positions of all components within' the pane. 
   { 
    setTitle("Average Computer"); // The window title. 
     
    // All JLabel Objects. 
    score1L = new JLabel("Test 1: ", SwingConstants.RIGHT); 
    score2L = new JLabel("Test 2: ", SwingConstants.RIGHT); 
    score3L = new JLabel("Test 3: ", SwingConstants.RIGHT); 
    score4L = new JLabel("Test 4: ", SwingConstants.RIGHT); 
    weight1L = new JLabel("Weight of Test 1: ", 
SwingConstants.RIGHT); 
    weight2L = new JLabel("Weight of Test 2: ", 
SwingConstants.RIGHT); 
    weight3L = new JLabel("Weight of Test 3: ", 
SwingConstants.RIGHT); 
    weight4L = new JLabel("Weight of Test 4: ", 
SwingConstants.RIGHT); 
    averageL = new JLabel("Average: ", 
SwingConstants.RIGHT); 
    blankL = new JLabel("", SwingConstants.RIGHT); 
    blank2L = new JLabel("", SwingConstants.RIGHT); 
    blank3L = new JLabel("", SwingConstants.RIGHT); 
     
    // All JTextField Objects, size 10 characters. 
    score1TF = new JTextField(10); 
    score2TF = new JTextField(10); 
    score3TF = new JTextField(10); 
    score4TF = new JTextField(10); 
    weight1TF = new JTextField(10); 
    weight2TF = new JTextField(10); 
    weight3TF = new JTextField(10); 
    weight4TF = new JTextField(10); 
    averageTF = new JTextField(10); 
     
    // Calculate Button Object and Handler 
    calculateAverageB = new JButton("Get Average"); 
    caHandler = new CalculateButtonHandler(); 
    calculateAverageB.addActionListener(caHandler); 
     
 8
    // Clear Button Object and Handler 
    clearB = new JButton("Clear"); 
    clHandler = new ClearButtonHandler(); 
    clearB.addActionListener(clHandler); 
     
    // Exit Button Object and Handler 
    exitB = new JButton("Exit"); 
    ebHandler = new ExitButtonHandler(); 
    exitB.addActionListener(ebHandler); 
     
    // Settin the grid and obtaining the pane. 
    Container pane = getContentPane(); 
    pane.setLayout(new GridLayout(6,3)); 
     
    // Placement of objects on the pane. 
    pane.add(score1L); 
    pane.add(score1TF); 
    pane.add(weight1L); 
    pane.add(weight1TF);    
    pane.add(score2L); 
    pane.add(score2TF); 
    pane.add(weight2L); 
    pane.add(weight2TF); 
    pane.add(score3L); 
    pane.add(score3TF); 
    pane.add(weight3L); 
    pane.add(weight3TF);    
    pane.add(score4L); 
    pane.add(score4TF); 
    pane.add(weight4L); 
    pane.add(weight4TF);     
      
    pane.add(averageL); 
    pane.add(averageTF); 
    pane.add(blankL); 
    pane.add(blank2L); 
    pane.add(blank3L); 
    pane.add(calculateAverageB); 
    pane.add(clearB); 
    pane.add(exitB); 
     
    setSize(WIDTH, HEIGHT); 
    setVisible(true); 
    setDefaultCloseOperation(EXIT_ON_CLOSE); 
   } 
    
 9
  private class CalculateButtonHandler implements ActionListener 
   // Listens for events on Calculate Button. 
   // Tells the program what to do with the test scores and weights 
   // when the button is invoked. 
   { 
   public void actionPerformed(ActionEvent e) 
   { 
double score1, score2, score3, score4, average, weight1, weight2, weight3, weight4; 
       
      score1 = 
Double.parseDouble(score1TF.getText()); 
      score2 = 
Double.parseDouble(score2TF.getText()); 
      score3 = 
Double.parseDouble(score3TF.getText()); 
      score4 = 
Double.parseDouble(score4TF.getText()); 
      weight1 = 
Double.parseDouble(weight1TF.getText()); 
      weight2 = 
Double.parseDouble(weight2TF.getText()); 
      weight3 = 
Double.parseDouble(weight3TF.getText()); 
      weight4 = 
Double.parseDouble(weight4TF.getText()); 
      average = 
(score1*weight1+score2*weight2+score3*weight3+score4*weight4); 
   averageTF.setText("" + average); 
     } 
   } 
    
  private class ClearButtonHandler implements ActionListener 
    // Listens for events on the Clear Button. 
    // Tells the program how to clear the text fields 
    // when the button is invoked. 
  { 
   public void actionPerformed(ActionEvent e) 
   { 
    score1TF.setText(""); 
    score2TF.setText(""); 
    score3TF.setText(""); 
    score4TF.setText(""); 
    weight1TF.setText(""); 
    weight2TF.setText(""); 
    weight3TF.setText(""); 
    weight4TF.setText(""); 
 10
    averageTF.setText(""); 
   } 
  } 
   
  private class ExitButtonHandler implements ActionListener 
   // Listens for events on the Exit Button. 
   // Tells the program to close when the Exit Button is invoked. 
   { 
    public void actionPerformed(ActionEvent e) 
     { 
      System.exit(0); 
     } 
   }      
     
  public static void main(String[] args) 
   { 
    // Creation of GUI window. 
    testAverageGUI testObject = new testAverageGUI(); 
   } 
 }// ... End of class testAverageGUI()  
 
Testing 
The algorithm test mentioned previously returned a weighted average of 92.0 and the 
buttons work as intended.  The test plan was successful.   
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 11
Question 2 
(B) Chapter 6, Programming Exercise #2, pp. 356 
 
Program Specification 
Write a GUI program that converts seconds to years, weeks, days, hours, and minutes.  
For this program assume 1 year = 365 days. 
 
Analysis  
This program is expected to create a GUI pane that accepts an integer value of seconds 
and turns those seconds into years, weeks, days, hours, and minutes.  The program will 
have a calculate button and an exit button.   
Program Inputs – An integer amount of seconds. 
Program Outputs – The corresponding amount of years, weeks, days, hours, and 
minutes. 
Formula or Relations 
1 year = 31449600 seconds 
1 week = 605800 seconds 
1 day = 86400 seconds 
1 hour = 3600 seconds 
1 minute = 60 seconds 
 
Design 
 Initial Algorithm 
1. Generate the GUI pane. 
2. Accept input seconds from the user. 
3. Process input. 
4. Output the corresponding amount of years, weeks, days, hours, and minutes. 
Refined Algorithm 
1. Generate the GUI pane. 
2. Accept an integer value of seconds from the user in a text field. 
3. Process the input. 
i. 1 year = 31449600 seconds 
ii. 1 week = 605800 seconds 
iii. 1 day = 86400 seconds 
iv. 1 hour = 3600 seconds 
v. 1 minute = 60 seconds 
4. Output the years, weeks, days, hours, and minutes the input seconds corresponds 
to, in a text field. 
 
 
 
 
 
 
 
 
 12
Methods 
 
Class CalculateButtonHandler( ) 
 This class listens for an event to occur on the calculate button.  Once the button is 
invoked, it tells the program what to do with the input to arrive at and display the years, 
weeks, days, hours, and minutes. 
 
Class ExitButtonHandler( ) 
 This class listens for an event to occur on the exit button.  Once the button is 
invoked, it tells the program to close. 
 
Test Plan 
All errors will result from faulty input.  The program will only accept integer values for 
seconds, but will output all other values as double.  
 
Algorithm Test 
Suppose the input amount of seconds was 31449600 (1 year).   
The program will output: 364 days (since it rounds down after a certain point), 52 weeks, 
1 year, 8736.0 hours, and 524160 minutes. 
 
Implementation 
//----------------------------------------------------------------------------- 
//  secondsBreakDownGUI.java 
//  This program is a GUI program with an interface. It takes in an amount of seconds 
//  and turns the seconds into years, weeks, days, hours, and minutes. 
//  Author: Andrew Butcher 
//  CS110 Section 007 
//  Lecturer: Don Adjeroh 
//  Lab Section: 010 
//  Lab Instructor: Matt Williamson 
//  Last Modified: 11/13/06 
//----------------------------------------------------------------------------- 
import javax.swing.*; 
import java.awt.*; 
import java.awt.event.*; 
 
public class secondsBreakDownGUI extends JFrame 
{ 
 // Width and height of the window pane. 
 private static final int WIDTH = 400; 
 private static final int HEIGHT = 300; 
  
 // Declaration of all JLavel, JTextField, and JButton objects. 
 private JLabel secondsL, yearsL, weeksL, daysL, hoursL, minutesL; 
 private JTextField secondsTF, yearsTF, weeksTF, daysTF, hoursTF, minutesTF; 
 private JButton exitB, calcB; 
 13
  
 private CalculateButtonHandler caHandler; 
 private ExitButtonHandler ebHandler; 
  
 public secondsBreakDownGUI() 
  // Declares all objects, and positions of objects within' the pane. 
 { 
  // Title of the window. 
  setTitle("Second Converter"); 
   
  // All JLabel objects. 
  secondsL = new JLabel("Seconds: ", SwingConstants.RIGHT); 
  yearsL = new JLabel("Years: ", SwingConstants.RIGHT); 
  weeksL = new JLabel("Weeks: ", SwingConstants.RIGHT); 
  daysL = new JLabel("Days: ", SwingConstants.RIGHT); 
  hoursL = new JLabel("Hours: ", SwingConstants.RIGHT); 
  minutesL = new JLabel("Minutes: ", SwingConstants.RIGHT);  
   
  // All JTextField objects. 
  secondsTF = new JTextField(20); 
  yearsTF = new JTextField(20); 
  weeksTF = new JTextField(20); 
  daysTF = new JTextField(20); 
  hoursTF = new JTextField(20); 
  minutesTF = new JTextField(20); 
   
  // Exit Button. 
  exitB = new JButton("Exit"); 
  ebHandler = new ExitButtonHandler(); 
  exitB.addActionListener(ebHandler); 
   
  // Calculation Button. 
  calcB = new JButton ("Calculate"); 
  caHandler = new CalculateButtonHandler(); 
  calcB.addActionListener(caHandler); 
   
  // Sets the grid and creates the pane. 
  Container pane = getContentPane(); 
  pane.setLayout(new GridLayout(7,2)); 
   
  // Position of all objects on the pane. 
  pane.add(secondsL); 
  pane.add(secondsTF); 
  pane.add(yearsL); 
  pane.add(yearsTF); 
  pane.add(weeksL); 
 14
  pane.add(weeksTF); 
  pane.add(daysL); 
  pane.add(daysTF); 
  pane.add(hoursL); 
  pane.add(hoursTF); 
  pane.add(minutesL); 
  pane.add(minutesTF); 
  pane.add(calcB); 
  pane.add(exitB); 
 
  setSize(WIDTH, HEIGHT); 
  setVisible(true); 
  setDefaultCloseOperation(EXIT_ON_CLOSE); 
 } 
private class CalculateButtonHandler implements ActionListener 
    // Listens for events on Calculate Button. 
    // Tells the program what to do with the seconds input 
    // when the button is invoked. 
{ 
 public void actionPerformed(ActionEvent e) 
  { 
   double seconds, years, weeks, days, hours, minutes; 
    
   seconds = Double.parseDouble(secondsTF.getText()); 
    
   years = seconds / 31449600; 
   weeks = seconds / 604800; 
   days = seconds / 86400; 
   hours = seconds / 3600; 
   minutes = seconds / 60; 
    
   yearsTF.setText("" + years); 
   weeksTF.setText("" + weeks); 
   daysTF.setText("" + days); 
   daysTF.setText("" + days); 
   hoursTF.setText("" + hours); 
   minutesTF.setText("" + minutes); 
  } 
} 
  
 private class ExitButtonHandler implements ActionListener 
   // Listens for events on the Exit Button. 
   // Tells the program to close when the Exit Button is invoked. 
 { 
  public void actionPerformed(ActionEvent e) 
   { 
 15
    System.exit(0); 
   } 
 }  
  
 public static void main(String[] args) 
 { 
  // Creation of the GUI window. 
  secondsBreakDownGUI breakDownObject = new 
secondsBreakDownGUI(); 
 } 
}// ... End of secondsBreakDownGUI()  
 
Testing 
The algorithm test mentioned previously results in values of; 1.0 years, 52.0 weeks, 364 
days, 8736.0 hours, and 524160.0 minutes.  Test was successful. 
 
 
  
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 16
Question 3 
Chapter 9, Programming Exercise #13, pp. 607 
 
Program Specifications 
a. Write a method createArithmeticSeq( ) that prompts the user to input two numbers, 
first and diff.  The method then creates a one-dimensional array of 16 elements ordered in 
an arithmetic sequence.  It also outputs the arithmetic sequence.  
b. Write a method matricize( ) that takes a one-dimensional array of 16 elements and a 
two-dimensional array of 4 rows and 4 columns as parameters.  This method puts the 
elements of the one-dimensional array into the two-dimensional array.  
c. Write a method reverseDiagonal( ) that reverses both diagonals of a two-dimensional 
array.  
d. Write a method magicCheck( ) that takes a one-dimensional array of size 16, a two-
dimensional array of 4 rows and 4 columns, and the sizes of the arrays as parameters.  
This method puts the elements of the one-dimensional array into the two-dimensional 
array.   
e. Write a method printMatrix( ) that outputs the elements of a two-dimensional array, 
one row per line.  This output should be as close to a square form as possible.  
f.  Amass all aforementioned methods into a program of class MagicSquare( ) that tests 
the various methods.  
g. JOptionPane dialog boxes should be used to obtain input from the user. 
h. The user should be given the option to read input from a file (and store outputs in a 
file) or to read input from the command line. 
 
Analysis 
This program is expected to take in two integers, a starting number, and the difference 
between each number in the sequence and create the sequence.  The program then 
switches the diagonals of the matrix created and if the sum of each row, column, and 
diagonal equal the sum of the original sequence divided by 4, then the square is a magic 
square. 
Program Inputs – The first number in the sequence (int) and the difference between 
each term in the sequence (int). 
Program Outputs – The sequence array, the two-dimensional matrix array, and a 
statement, which indicates whether or not the sequence is a magic square. 
Formula or Relations 
None 
 
Design 
 Initial Algorithm 
1. Read Input from the user. 
2. Process Input from the user. 
3. Output results. 
Refinement 
1. Using GUI dialog boxes, or file input, read input from the user. 
2. Create one-dimensional array sequence and two-dimensional array sequence.  
Switch diagonals and determine whether or not the sequence is a magic square. 
 17
3. Display the array, the matrix, and the switched matrix then output whether or not 
the sequence is a magic square through a GUI dialog box, or out file. 
 
Methods 
 
Method createArithmeticSeq( ) 
 Through a loop, this method creates a one-dimensional array based on the first 
term and the difference variable. 
 
Method matricize( ) 
 This method stores the one-dimensional sequence array into a two-dimensional 
matrix array. 
 
Method reverseMatrix( ) 
 This method, through a loop, reverses the diagonals of the two-dimensional 
matrix. 
 
Method magicCheck( ) 
 This method separately adds all rows, columns, and diagonals of the updates 
matrix. 
 
Method printMatrix( ) 
 This method , through a loop, prints the elements of the matrix row by row.  
 
Test Plan 
If integers are not input for first and diff values, the program will fail.  Other than, that, 
there isn’t much room for error.  
 
Algorithm Test 
Suppose the first term entered was 21 and the diff term entered was 5. 
The initial sequence would appear as follows: 
21 26 31 36 41 46 51 56 61 66 71 76 81 86 91 96 
The matrix would appear as follows: 
21 26 31 36 
41 46 51 56 
61 66 71 76 
81 86 91 96 
The reversed matrix would appear as follows: 
96 26 31 81 
41 71 66 56 
61 51 46 76 
36 86 91 21 
 
21 + 26 + 31 + 36 + 41 + 46 + 51 + 56 + 61 + 66 + 71 + 76 + 81 + 86 + 91 + 96 / 4 = 234 
96 + 26 + 31 + 81 = 234 61 + 51 + 46 + 76 = 234 96 + 41 + 61 + 36 = 234 
41 + 71 + 66 + 56 = 234 36 + 86 + 91 + 21 = 234 26 + 71 + 51 + 86 = 234 
 18
31 + 66 + 46 + 91 = 234 81 + 56 + 76 + 21 = 234 
It is a magic square. 
 
Implementation 
//----------------------------------------------------------------------------- 
//  MagicSquare.java 
//  This program creates an arithmetic sequence based on a starting number and 
//  the difference between each number in the sequence.  It creates a two-dimensional 
//  array of the arithmetic sequence (matrix) and outputs whether or not the sequence  
//  created is a magic square.  
//  Author: Andrew Butcher 
//  CS110 Section 007 
//  Lecturer: Don Adjeroh 
//  Lab Section: 010 
//  Lab Instructor: Matt Williamson 
//  Last Modified: 11/16/06 
//----------------------------------------------------------------------------- 
import javax.swing.*; 
import java.util.*; 
import java.io.*; 
 
public class MagicSquare 
{ 
  
 static int[] sequence; 
 static int[][] matrix; 
 private static boolean option; 
 static PrintWriter outFile; 
 static Scanner inFile;  
  
 public static void inputOption() 
 { 
  String optionStr; 
  char optionChar; 
  optionStr = JOptionPane.showInputDialog("Would you like to input from a file or the 
command line? Enter f for file, or c for command line."); 
  optionChar = optionStr.charAt(0); 
  if  (optionChar == 'f' || optionChar == 'F') 
  { 
   option = true; 
    } 
  else if (optionChar == 'c' || optionChar == 'C') 
   { 
    option = false; 
    }  
 } 
 19
 
 public static void createArithmeticSeq() throws FileNotFoundException 
 { 
  String firstStr, diffStr; // Strings necessary for JOptionPane 
  int first, diff; 
  String seqStr = ""; 
  first = 0; 
  diff = 0; 
  // JOptionPane's for input 
   if (option == false) 
   { 
    firstStr = JOptionPane.showInputDialog("Please enter the first number of the 
arithmetic sequence."); 
    first = Integer.parseInt(firstStr); // Parsing out the first number of sequence 
    diffStr = JOptionPane.showInputDialog("Please enter the difference between each 
term in the sequence."); 
    diff = Integer.parseInt(diffStr); // Parsing out the difference between each term 
    } 
   else 
    { 
     first = inFile.nextInt(); 
     diff = inFile.nextInt(); 
    } 
   
  sequence = new int[16]; 
   
  for (int i=0; i < sequence.length; i++) 
   { 
    sequence[i] = first + diff*i; 
   } 
  if (option == false) 
  { 
  for (int k = 0; k < 16; k++) 
   { 
    System.out.printf("%4d", sequence[k]); 
    /*seqStr = sequence[k]+ "";  
    JOptionPane.showMessageDialog(null, seqStr, "Arithmetic 
Sequence",JOptionPane.INFORMATION_MESSAGE); */ 
   } 
  } 
 else  
 { 
  for (int k = 0; k < 16; k++) 
   { 
    outFile.printf("%4d", sequence[k]); 
   } 
 20
 } 
   
  }// ... End of createArithmeticSeq() 
 public static void matricize() 
 { 
    int row = 0, col; 
  matrix = new int[4][4]; 
  // Sets two dimensional array row by row. (May be counterintuitive) 
  for (col = 0; col < matrix[row].length; col++) 
  { 
   row = 0; 
   matrix[row][col] = sequence[col]; 
   } 
  for (col = 0; col < matrix[row].length; col++) 
  { 
   row = 1; 
   matrix[row][col] = sequence[col + 4]; 
   } 
  for (col = 0; col < matrix[row].length; col++) 
  { 
   row = 2; 
   matrix[row][col] = sequence[col + 8]; 
   } 
  for (col = 0; col < matrix[row].length; col++) 
  { 
   row = 3; 
   matrix[row][col] = sequence[col + 12]; 
   }       
 }// ... End of matricize() 
  
 public static void reverseDiagonal() 
 { 
  int row, col; 
  int temp; 
  for (row = 0; row < matrix.length / 2; row++) 
  { 
   temp = matrix[row][row]; 
   matrix[row][row] = matrix[matrix.length - 1 - row][matrix.length - 1 - row]; 
    matrix[matrix.length - 1 - row][matrix.length - 1 - row] = temp; 
  } 
  for (row = 0; row < matrix.length / 2; row++) 
  { 
   temp = matrix[row][matrix.length - 1 - row]; 
   matrix[row][matrix.length -1 - row] = matrix[matrix.length - 1 - row][row]; 
   matrix[matrix.length - 1 - row][row] = temp; 
  } 
 21
 }// ... End of reverseDiagonal() 
  
 public static void printMatrix() 
 {  
  int row, col; 
   
  if (option == false) // Check the user's option for file I/O or command line. 
  { 
   // Prints matrix row by row to create a square shaped matrix. 
   for (col = 0; col < matrix.length; col++) 
   { 
    row = 0; // First Row 
    System.out.printf("%3d", matrix[row][col]); 
    } 
   System.out.println("");  
   for (col = 0; col < matrix.length; col++) 
   { 
    row = 1; // Second Row 
    System.out.printf("%3d", matrix[row][col]); 
    } 
   System.out.println(""); 
   for (col = 0; col < matrix.length; col++) 
   { 
    row = 2; // Third Row 
    System.out.printf("%3d", matrix[row][col]); 
    } 
   System.out.println(""); 
   for (col = 0; col < matrix.length; col++) 
   { 
    row = 3; // Fourth Row 
    System.out.printf("%3d", matrix[row][col]); 
    } 
  } 
  else   
  { 
     // Prints matrix row by row to create a square shaped matrix. 
   for (col = 0; col < matrix.length; col++) 
   { 
    row = 0; // First Row 
    outFile.printf("%3d", matrix[row][col]); 
    } 
   outFile.println("");  
   for (col = 0; col < matrix.length; col++) 
   { 
    row = 1; // Second Row 
    outFile.printf("%3d", matrix[row][col]); 
 22
    } 
   outFile.println(""); 
   for (col = 0; col < matrix.length; col++) 
   { 
    row = 2; // Third Row 
    outFile.printf("%3d", matrix[row][col]); 
    } 
   outFile.println(""); 
   for (col = 0; col < matrix.length; col++) 
   { 
    row = 3; // Fourth Row 
    outFile.printf("%3d", matrix[row][col]); 
    }   
  }     
 }// ... End of printMatrix() 
  
  
 public static void magicCheck() 
 { 
  int sum = 0, magicNumber, row, col; 
  int rowSum1 = 0, rowSum2 = 0, rowSum3 = 0, rowSum = 0, colSum1 = 0, colSum2 = 
0, colSum3 = 0, colSum = 0, diagSum1 = 0, diagSum = 0; 
   
   for (int j = 0; j < sequence.length; j++) 
   { 
    sum = sum + sequence[j]; 
   } 
    magicNumber = sum / 4; 
    
   // Sum of Rows  
   for (col = 0; col < matrix.length; col++) 
   { 
    row = 0; 
    rowSum = rowSum + matrix[row][col]; 
    } 
   for (col = 0; col < matrix.length; col++) 
   { 
    row = 1; 
    rowSum1 = rowSum1 + matrix[row][col]; 
    } 
   for (col = 0; col < matrix.length; col++) 
   { 
    row = 2; 
    rowSum2 = rowSum2 + matrix[row][col]; 
    } 
   for (col = 0; col < matrix.length; col++) 
 23
   { 
    row = 0; 
    rowSum3 = rowSum3 + matrix[row][col]; 
    }    
   // ...  
    
   // Sum of Columns   
   for (row = 0; row < matrix.length; row++) 
   { 
    col = 0; 
    colSum = colSum + matrix[row][col]; 
   } 
   for (row = 0; row < matrix.length; row++) 
   { 
    col = 1; 
    colSum1 = colSum1 + matrix[row][col]; 
   } 
   for (row = 0; row < matrix.length; row++) 
   { 
    col = 2; 
    colSum2 = colSum2 + matrix[row][col]; 
   } 
   for (row = 0; row < matrix.length; row++) 
   { 
    col = 3; 
    colSum3 = colSum3 + matrix[row][col]; 
   } 
   // ... 
    
   // Sum of Diagonals 
   for (row = 0,col = 0; row < matrix.length && col < matrix.length; row++) 
   {  
   diagSum = diagSum + matrix[row][col]; 
   col = col++; 
   } 
    
   for (col = 0, row = 3; col < matrix.length && row < matrix.length; col++) 
   {  
    diagSum1 = diagSum1 + matrix[row][col]; 
    row--; 
   } 
     //...  
    
   // Begin of magic check 
   if (rowSum == magicNumber && rowSum1 == magicNumber && rowSum2 == 
magicNumber && rowSum3 == magicNumber && 
 24
   colSum == magicNumber && colSum1 == magicNumber && 
colSum2 == magicNumber && colSum3 == magicNumber && 
   diagSum == magicNumber && diagSum1 == magicNumber) 
   { 
         if (option == false) 
     { 
      System.out.println("It is a magic square."); 
     } 
     else 
     { 
      outFile.println("It is a magic square."); 
     } 
   } 
   else 
   { 
     if (option == false) 
   { 
     System.out.println("It is not a magic square."); 
    } 
     else 
  { 
      outFile.println("It is not a magic square."); 
  } 
    } 
} 
 public static void main(String[] args) throws FileNotFoundException 
 {  
   try { 
     outFile = new PrintWriter("c:\\magicsquare.txt"); 
     inFile = new Scanner(new FileReader("c:\\sequence.txt"));  
  inputOption(); 
  //Array methods don't require parameters, arrays can be changed anywhere within the 
program. 
  createArithmeticSeq(); 
  System.out.println(""); 
  outFile.println(""); 
  System.out.println(""); 
  outFile.println(""); 
  matricize(); 
  printMatrix(); 
  System.out.println(""); 
  outFile.println(""); 
  System.out.println(""); 
  outFile.println(""); 
  reverseDiagonal(); 
  printMatrix(); 
 25
  System.out.println(""); 
  outFile.println(""); 
  System.out.println(""); 
  outFile.println(""); 
  magicCheck(); 
   if (option == true) 
    { 
     inFile.close(); 
     outFile.close(); 
     } 
   } 
   catch (FileNotFoundException e) 
   { 
     JOptionPane.showMessageDialog(null, "File not found!", "Error", 
JOptionPane.WARNING_MESSAGE); 
   } 
 }// ... End of main() 
}// ... End of class MagicSquare 
 
 
Test Results 
Both command line, and file input instances ran successfully.  A custom 
FileNotFoundException error was created, in the form of a try/catch block to inform user 
of file not found error.  
 
 26