验证一组数字是否magic square

以下是「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 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值