Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/tensorflow/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 将外部文件转换为二维数组_Java_Arrays - Fatal编程技术网

Java 将外部文件转换为二维数组

Java 将外部文件转换为二维数组,java,arrays,Java,Arrays,所以我一直在研究如何使用扫描仪将外部文件放入2d阵列。然而,我真的不明白如何使它工作,我希望我能得到一些帮助,如何写它。例如,如果我有一个类似(5x5)的文件: 45 67 89 12-3 -3-6-7-4-9 96 81-8 52 12 14-7 72 29-1 1943286387 然后我用扫描器读取文件(非常粗略的轮廓): 如何使用此格式将此数据存储到二维数组中?我真的不确定它是如何工作的,我有一个考试在几周后。我本来打算问我的教授,但他最近几天没来。有人能告诉我如何将文件存储到2d数组中

所以我一直在研究如何使用扫描仪将外部文件放入2d阵列。然而,我真的不明白如何使它工作,我希望我能得到一些帮助,如何写它。例如,如果我有一个类似(5x5)的文件:

45 67 89 12-3

-3-6-7-4-9

96 81-8 52 12

14-7 72 29-1

1943286387

然后我用扫描器读取文件(非常粗略的轮廓):


如何使用此格式将此数据存储到二维数组中?我真的不确定它是如何工作的,我有一个考试在几周后。我本来打算问我的教授,但他最近几天没来。有人能告诉我如何将文件存储到2d数组中吗?如果还有其他更有效的方法,我愿意接受所有的想法(仍然是初学者)。非常感谢您的帮助。

创建一个5乘5的2D int数组,并调用扫描仪的
nextInt()
(意味着它必须是int而不是字符串,否则会出错)

试试这个代码

 int array[][] = new int[5][5];
    int counter1 = 0;
    int counter2 = 0;
    Scanner reader = new Scanner(new File("Insert File Location"));
    while(reader.hasNext())
    {
        array[counter1][counter2++] = reader.nextInt();
        array[counter1][counter2++] = reader.nextInt();
        array[counter1][counter2++] = reader.nextInt();
        array[counter1][counter2++] = reader.nextInt();
        array[counter1][counter2++] = reader.nextInt();
        ++counter1;
        counter2 = 0;
    }

此问题已被多次询问和回答。可能重复
 int array[][] = new int[5][5];
    int counter1 = 0;
    int counter2 = 0;
    Scanner reader = new Scanner(new File("Insert File Location"));
    while(reader.hasNext())
    {
        array[counter1][counter2++] = reader.nextInt();
        array[counter1][counter2++] = reader.nextInt();
        array[counter1][counter2++] = reader.nextInt();
        array[counter1][counter2++] = reader.nextInt();
        array[counter1][counter2++] = reader.nextInt();
        ++counter1;
        counter2 = 0;
    }