我在java的二维数组(字符串数据类型)中遇到了一个问题。我有另一个名为arr的数组,我想在单个字符串数组a中输入名称,并将这些名称复制到2d数组的第0行的列中。请帮帮我!
import java.util.Scanner;
public class Strings
{
public static void main(String[] args)// main function
{
String qwert[][]=new String[5][];
Scanner reader = new Scanner(System.in);
System.out.println("enter no of columns");
String arr[]= new String[5];
int t=reader.nextInt();
System.out.println("now arr input");
for(int k=0;k<t;k++)
arr[k]=reader.next();
for(int j=0;j<t;j++)
{
qwert[0][j]=arr[j];
}
for(int b=0;b<t;b++)
System.out.println(qwert[0][b]);
}//main function ends
}//class ends
发布于 2018-06-10 00:55:45
String qwert[][] = new String[5][];
创建了一个由5个数组组成的数组,所有数组都为空,因此为quert[0] = null
。当你尝试输入你的for
,qwert[0][j] = arr[j]
,qwert[0]
是空的,所以你会得到一个NullPointerException
。在使用qwert[i]
之前,您需要对其进行初始化。
// you need to initialize qwert[0]
qwert[0] = new String[t];
for(int j = 0; j < t; j++)
{
qwert[0][j] = arr[j];
}
https://stackoverflow.com/questions/50776493
复制相似问题