我的任务是编写一个询问用户输入的程序,该方法将返回输入是否形成幻方.不管我进入控制台什么,程序都会返回我输入了一个魔方.我想念什么?
幻方定义:如果行,列和对角线的总和相同,则二维数组就是幻方.
here is the Code:
public class MagicSquares {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
ArrayList ints = new ArrayList();
int current = 0;
do{
System.out.print("Enter an int. Enter -1 when done>");
current = Integer.parseInt(in.nextLine());
}while(current != -1);
int numInputs = ints.size();
int square = (int) Math.sqrt(numInputs);
if(square*square == numInputs){
int[][] intSquare = new int[square][square];
int x = 0;
while(x < numInputs){
for(int y = 0; y < square; ++y){
for(int z = 0; z < square; ++z){
intSquare[y][z] = ints.get(x);
++x;
}
}
}
if(isMagicSquare(intSquare)){
System.out.println("You entered a magic square");
}else{
System.out.println("You did not enter a magic square");
}
}else{
System.out.println("You did not enter a magic square. " +
"You did not even enter a square...");
}
}
private static Boolean isMagicSquare(int[][] array){
int side = array.length;
int magicNum = 0;
for(int x = 0; x < side; ++x){
magicNum =+ array[0][x];
}
int sumX = 0;
int sumY = 0;
int sumD = 0;
for(int x = 0; x > side; ++x){
for (int y = 0; y < side; ++y){
sumX =+ array[x][y];
sumY =+ array[y][x];
}
sumD =+ array[x][x];
if(sumX != magicNum || sumY != magicNum || sumD != magicNum){
return false;
}
}
return true;
}
}