因此,我一直在尝试创建一个程序,该程序允许用户从包含各种单词的正方形中选择所需的行和列。现在,该代码将要求用户输入一行,如果他们输入2,它将打印出“ LAVA”,因为这是正方形的第二行。问题是我不知道如何创建一种可以打印出一列的方法,因此,如果用户键入1,他们将得到“ PLOT”,因为这是第一列中包含的单词。我的代码当前如下:
import java.util.Scanner;
public class MagicSquare {
public static void main(String[] args)
{
char[][] magicSquare = {
{,},
{'P', 'R', 'E', 'Y'},
{'L', 'A', 'V', 'A'},
{'O', 'V', 'E', 'R'},
{'T', 'E', 'N', 'D'},
};
displayRow(magicSquare);
displayCol(magicSquare);
}
static void displayRow(char[][] rowIn)
{
Scanner input = new Scanner(System.in);
int row;
System.out.println("What row do you want to display (1-4): ");
row = input.nextInt();
while(row<1 || row>4)
{
System.out.println("Invalid row number!!");
System.out.println("Enter again (1-4 only): ");
row = input.nextInt();
}
System.out.println();
for(int i = 4; i <= rowIn[1].length; i++)
{
System.out.println(rowIn[row]);
System.out.println();
}
}
static void displayCol(char[][] colIn)
{
Scanner input = new Scanner(System.in);
int col;
System.out.println("What column do you want to display (1-4): ");
col = input.nextInt();
while(col<1 || col>4)
{
System.out.println("Invalid col number!!");
System.out.println("Enter again (1-4 only): ");
col = input.nextInt();
}
System.out.println();
for(int i = 4; i <= colIn[1].length; i++)
{
System.out.println(colIn[col]);
}
}
}
displayCol不起作用,因为它做与displayRow完全相同的操作,但是我不知道如何获取它来打印列而不是行。任何帮助表示赞赏。
您的循环应位于具有变化的行的特定列上。就像是,
我用您指定的输入进行了测试,我得到