gpt4 book ai didi

java - 读取值以插入二维数组

转载 作者:行者123 更新时间:2023-11-30 02:40:35 24 4
gpt4 key购买 nike

我正在做一项作业,需要从文件中读取示例输入并将其插入到二维数组中。以下是输入示例:

5 6
1 3 4 B 4 3
0 3 5 0 0 9
0 5 3 5 0 2
4 3 4 0 0 4
0 2 9 S 2 1

5 和 6 是数组的维度。用户必须能够一次输入多个像这样的数组,当用户输入-1时程序结束。这是我到目前为止的代码,似乎没有按预期工作(我打印出数组以确保代码工作):

public static void main (String[] args){
Scanner sc = new Scanner(System.in);
int arHeight = sc.nextInt();
int arWidth = sc.nextInt();
sc.useDelimiter(" ");
String[][] map = new String[arHeight][arWidth];

for(int i=0; i<arHeight; i++){
for(int j=0; j<arWidth; j++){
map[i][j] = sc.nextLine();
}//end inner for
}//end outter for

for(int i=0; i<arHeight; i++){
for(int j=0; j<arWidth; j++){
System.out.print(map[i][j] + " ");
}//end inner for
}//end outter for
}

作业指出我不能使用递归并且必须使用二维数组。我看过其他问题,但似乎仍然无法弄清楚。感谢您的帮助!!

最佳答案

你读了整行 i*j 次

    for(int i=0; i<arHeight; i++){
for(int j=0; j<arWidth; j++){
map[i][j] = sc.nextLine();

您还将所有数据保存在字符串数组中,我不知道为什么。解决办法如下:

public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int arHeight = sc.nextInt();
int arWidth = sc.nextInt();

int[][] map = new int[arHeight][arWidth];

for(int i=0; i<arHeight; i++){
for(int j=0; j<arWidth; j++){
map[i][j] = sc.nextInt();
}//end inner for
}//end outter for

for(int i=0; i<arHeight; i++){
for(int j=0; j<arWidth; j++){
System.out.print(map[i][j] + " ");
}//end inner for
}

}

然后尝试使用

char[][] map = new char[arHeight][arWidth];

在 for 循环中:

if(sc.next().charAt(0) != " ") map[i][j] =sc.next().charAt(0);

这样你应该读取所​​有不是“”的字符。

关于java - 读取值以插入二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41862750/

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