gpt4 book ai didi

java - 从用户获取一个字符串并将其字符放入二维数组中

转载 作者:行者123 更新时间:2023-12-02 04:07:17 24 4
gpt4 key购买 nike

我想让用户输入一个字符串,并且我想在二维数组中获取它的字符
第一个用户输入数组的大小及其 n*n 数组,因此如果用户输入 4 例如,他将数组 4*4 2d 并且我想在他输入我的代码时打印输入

Scanner in=new Scanner(System.in);
int n=in.nextInt();
char arr[][]=new char[n][n];
String a;
for (int i=0;i<n;i++)
{
a=in.next(); //Eneter the sting
for (int j=0;j<n;j++)
{
for (int k=0;k<n;k++)
{
arr[j][k]=a.charAt(j); //i get the character in the array
}
}
}
System.out.println(Arrays.deepToString(arr)); //to check the array

如果用户输入

4
...#
.#.#
.#..
####

输出

[[#, #, #, #], [#, #, #, #], [#, #, #, #], [#, #, #, #]]

预期输出作为用户输入

[[., ., ., #], [., #, ., #], [., #, ., .], [#, #, #, #]]

我刚开始java 2天,二维数组我不太擅长
如何按照我的预期将其填充到二维数组中最后一件事我想打印数组中每个 # 的索引,例如在 1 4 中找到的第一行,在 2 2 2 3 中找到的第二行等等

最佳答案

您的循环太多,这是修改后的代码:

        Scanner in = new Scanner(System.in);
int n = in.nextInt();
char arr[][] = new char[n][n];
String a;

for (int i = 0; i < n; i++) {
a = in.next(); //Eneter the sting

for (int k = 0; k < n; k++) {

arr[i][k] = a.charAt(k); //i get the character in the array
}

}
System.out.println(Arrays.deepToString(arr));

// print indexes
for (int i = 0; i < n; i++) {

System.out.println("Line " + i);

for (int k = 0; k < n; k++) {

if (arr[i][k] == '#') {
// (print i+1 and k+1 instead of i and k, if you prefer)
System.out.print(i + " " + k);
}
}

System.out.println();

}

关于java - 从用户获取一个字符串并将其字符放入二维数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34153658/

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