以下是「Core Java for the Impatient」一书第一章的第14道习题及解答。
题目:
Write a program that reads a two-dimensional array of integers and determines whether it is a magic square (that is, whether the sum of all rows, all columns, and the diagonals is the same). Accept lines of input that you break up into individual integers, and stop when the user enters a blank line. For example, with the input
16 3 2 13 5 10 11 8 9 6 7 12 4 15 14 1 (Blank line)
your program should respond affirmatively.
解答:
思路
1. 使用元素是数组的ArrayList组装成square,把square的每一行、每一列、每一对角线都当成一个line来处理
2. 先计算第一行的和,然后依次扫描计算剩余的行、列和对角线的和,只要有不等于第一行和的,就认定不是magic square
代码
import java.util.ArrayList;
import