gpt4 book ai didi

java - 如何在java中创建幻方?

转载 作者:行者123 更新时间:2023-11-30 08:03:45 26 4
gpt4 key购买 nike

我的任务是编写一个程序,要求用户输入,该方法将返回输入是否形成幻方。无论我在控制台输入什么,程序都会返回我进入了幻方。我错过了什么?

魔方定义:如果行、列和对角线之和相同,则二维数组是魔方。

here is the Code:


public class MagicSquares {


public static void main(String[] args) {
Scanner in = new Scanner(System.in);
ArrayList<Integer> ints = new ArrayList<Integer>();
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;
}



}

最佳答案

  • 您没有保存输入的内容,因此 0x0 方 block 被传递给 isMagicSquare() .
  • 实现isMagicSquare()在很多方面都是错误的。
    • 条件x > side应该是 x < side .
    • 你必须检查sumD只有在计算完成之后。
    • 你必须初始化sumXsumY在计算它们之前。
    • 你应该使用+=而不是 =+计算总和。

更正:

让代码保存输入

do{
System.out.print("Enter an int. Enter -1 when done>");
current = Integer.parseInt(in.nextLine());
if (current != -1) ints.add(current); // add this line to the loop to read the input
}while(current != -1);

并更正isMagicSquare() .

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 sumD = 0;
for(int x = 0; x < side; ++x){
int sumX = 0;
int sumY = 0;
for (int y = 0; y < side; ++y){
sumX += array[x][y];
sumY += array[y][x];
}
sumD =+ array[x][x];
if(sumX != magicNum || sumY != magicNum){
return false;
}
}
return sumD == magicNum;
}

关于java - 如何在java中创建幻方?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36102091/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com