gpt4 book ai didi

java - 二维数组作为输入;存储在自己的二维数组中

转载 作者:行者123 更新时间:2023-12-01 09:54:36 24 4
gpt4 key购买 nike

对于作业,我必须读取如下所示的输入:

. . . . . . . . . . . . . * .
. . . . . . . . . . . . * . .
. . . . . . . . . . . . * * *
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
* * * * * * * * . . . . . . .
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .

并将其存储在包含字符串的数组中。现在我已经想出了这个,但是,我不知道如何以可以将其存储为数组的方式排列输入。

void readInputField(){
String inputField; //string in which input is stored
inputField = sc.nextLine(); //scans the input
String[][] fieldParts; //array in which I want to store Strings of inputField
fieldParts = new String[height][width]; //width and height are determined
//by earlier scanner input and correspond to the dimensions of the input array

fieldParts = inputField.split(" "); //error on this line, how to split the input
//as parts of the array?
}

最佳答案

在您发布所收到的确切错误之前,无法判断问题所在。就像上面的评论一样,如果您只是读取简单的字符,字符数组将是理想的选择。但对于字符串,如果您逐行读取输入,那么代码将在 for 循环内分割一行,如下所示。 (假设用户在提供每个输入行后单击“输入”)

String[][] fieldParts = new String[row][col];
int j = 0;
for(int i=0;i<row;i++)
{
String inputField = sc.nextLine();
String[] row = new String[col];
row = inputField.split(" ");
fieldParts[j] = row; //the row you just read
j++;
}

关于java - 二维数组作为输入;存储在自己的二维数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37344633/

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