gpt4 book ai didi

java - 如何在Java中获取二维动态数组的输入?

转载 作者:行者123 更新时间:2023-11-30 01:46:44 25 4
gpt4 key购买 nike

我正在编写一个代码,其中将从用户处获取输入并将其存储在二维动态数组中。我们知道没有。数组的行数。但数组的列数是动态的。

输入的格式如下:

3

sghjhlklj

ghgh

ytyhuj

由于首先输入 3,因此必须将三个后续字符串存储在数组中。

以下是我编写的代码片段。但它显示数组索引越界异常。

import java.util.Arrays;
import java.util.Scanner;

class Main
{
// Read a String from the standard input using Scanner
public static void main(String[] args)
{

Scanner in = new Scanner(System.in);

Integer no = in.nextInt();
System.out.println("You entered string "+no);
int z = 0,y=0 ;

char[][] arr = new char[no][];

for(z=0 ; z<no ; z++)
{
String s = in.nextLine();
String[] arrOfStr = s.split("");
for( y =0 ; y<arrOfStr.length ; y++)
{
arr[z][y]=arrOfStr[y].charAt(0);

}



}


in.close();
}
}

最佳答案

您的代码存在 3 个问题:

  1. 您永远不会初始化内部数组。使用arr[z] = new char[s.length()];来实现。
  2. 定义arrOfStr的方式。您用空白子字符串分割字符串。相反,只需使用 s 使用 charAt 即可,如下所示:arr[z][y] = s.charAt(y);
  3. 正如评论所建议的,nextInt 存在问题,未考虑 \n(输入)字符。因此,请使用 int no=Integer.parseInt(in.nextLine());,而不是使用 nextInt

最终的代码应如下所示:

for(z=0 ; z<no ; z++)
{
String s = in.nextLine();
arr[z] = new char[s.length()];
for( y =0 ; y<s.length() ; y++)
{
arr[z][y]=s.charAt(y);
}
}

关于java - 如何在Java中获取二维动态数组的输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57674762/

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