我正在尝试使用数组编写一个非常简单的 3x3 幻方游戏。
我的程序将要求用户每次输入三个数字(顶行、中间行、底行),然后将显示这些值。问题是我试图让我的程序验证用户是否输入了正确的值。
我不确定我会怎么做;我曾想过简单地声明固定值并进行比较/使用条件语句将用户的输入与这些常量值进行比较(在下面的代码中解释数组 d、e 和 f),但我也认为这并不完全正确,因为除了我要声明的值之外,还有许多可能的值可以组成一个幻方,当然,我不想在我的代码中变得那么多余。
我对数组还不是很熟悉,我是 Java 的初学者。我不确定在这里问这个问题是否可以,但我希望有人仍然会回应。这是相当重要的,因为它是一个学校项目。
我知道这些数字应该在水平、垂直和对角线上总共有 15 个。我不知道该怎么做。
虽然,我想我会坚持简单地制作条件语句(如果没有人会回答我上面的问题),因为我刚刚找到了一个包含所有 3x3 幻方的源,所以如果有人能教我如何比较用户定义的数组和程序员定义的数组,那会很好。
我写了一些代码来存储用户输入。
import java.util.*;
class arrayy
{
public static void main(String args[])
{
int[] a=new int[3];
int[] b=new int[3];
int[] c=new int[3];
int[] d={8,1,6};
int[] e={3,5,7};
int[] f={4,9,2};
Scanner sc=new Scanner(System.in);
System.out.println("Please enter the 3 numbers for the top row: ");
for(int j=0;j<3;j++)
a[j]=sc.nextInt();
System.out.println();
System.out.println("Please enter the 3 numbers for the middle row: ");
for(int j=0;j<3;j++)
b[j]=sc.nextInt();
System.out.println();
System.out.println("Please enter the 3 numbers for the bottom row: ");
for(int j=0;j<3;j++)
c[j]=sc.nextInt();
System.out.println("Your entry: ");
for (int i=0;i<a.length;i++)
System.out.print(a[i]+" ");
System.out.println();
for (int i=0;i<a.length;i++)
System.out.print(b[i]+" ");
System.out.println();
for (int i=0;i<a.length;i++)
System.out.print(c[i]+" ");
System.out.println();
System.out.println();
}
}