简体   繁体   English

二维数组中带有空格的字符串输入

[英]String input with spaces in 2D array

I want to take string inputs in java which is separated by spaces in a 2D array and display all the items in a separate line. 我想在java中获取字符串输入,该字符串由2D数组中的空格分隔,并在单独的行中显示所有项目。

eg: 例如:
input: 输入:

item1 3 5 项目1 3 5
item2 7 4 项目2 7 4

output: 输出:

item1 项目1
3 3
5 5
item2 item2
7 7
4 4

Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int b = sc.nextInt();
String array_of_items[][] = new String[a][b];
for(int i=0;i<a;i++)
{ 
  String str = sc.nextLine(); 
  String[] lineVector = str.split(" ");
  for(int j=0;j<b;j++)
  {
    array_of_items[i][j] = lineVector[j];
  }
}

for(int i=0;i<a;i++)
{
  for(int j=0;j<b;j++)
  {
    System.out.println(array_of_items[i][j]);
  }
}

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1 线程“主”中的异常java.lang.ArrayIndexOutOfBoundsException:1

The first String str = sc.nextLine(); 第一个String str = sc.nextLine(); reads the new line from int b = sc.nextInt(); int b = sc.nextInt();读取新行int b = sc.nextInt(); so your lineVector is empty => ArrayIndexOutOfBoundsException when you try to access lineVector[j] . 因此,当您尝试访问lineVector[j]时,您的lineVector为空=> ArrayIndexOutOfBoundsException The fix is to consume that line by adding a sc.nextLine(); 解决方法是通过添加sc.nextLine();来消耗该行sc.nextLine(); after int b = sc.nextInt(); int b = sc.nextInt(); .

Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int b = sc.nextInt();
sc.nextLine();
String array_of_items[][] = new String[a][b];
for (int i = 0; i < a; i++) {
    String str = sc.nextLine();
    String[] lineVector = str.split(" ");
    for (int j = 0; j < b; j++) {
        array_of_items[i][j] = lineVector[j];
    }
}
for (int i = 0; i < a; i++) {
    for (int j = 0; j < b; j++) {
        System.out.println(array_of_items[i][j]);
    }
}

Input 输入项

2
3
1 2 3
4 5 6

Output 输出量

1
2
3
4
5
6

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM