简体   繁体   English

将整数从文件存储到2D数组

[英]Storing integers from file to 2D array

I am trying to import similar to this 我正在尝试类似导入

5 5
1 1
3 3
1 1 1 1 1
1 0 1 0 1
1 0 1 0 1
1 0 0 0 1
1 1 1 1 1

files into 2D array but I am having hard time, this is my code so far, which does nothing, there aren't syntactic mistakes, so I don't get any errors but a blank console and I don't know what I did wrong. 文件进入2D数组,但是我很难过,这是到目前为止的代码,什么都不做,没有语法错误,所以除了空白的控制台之外我没有任何错误,我也不知道我做了什么错误。 The size of the array is the first 2 numbers inside the file. 数组的大小是文件中的前2个数字。

package main;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class oboroten {
public static void main(String[] args) {
    int x, y;
    x = y = 0;
    int[][] maze = new int[x][y];
    try {
        Scanner reader = new Scanner(new File("C:\\Users\\User\\Desktop\\mazes\\input.txt"));
        x = reader.nextInt();
        y = reader.nextInt();
        for (int i = 0; i < x; i++){
            for (int j = 0; j < y; j++){
                maze[i][j] = reader.nextInt();
                System.out.println(maze[i][j]);
            }
        }       
        reader.close();
    } catch (FileNotFoundException e1) {
        System.out.println("Problem with the file");
        e1.printStackTrace();
    }
}}

You initial you array with the size 0. So nothing will be addet there. 您以大小为0的数组作为初始数组。因此,此处不会再有其他内容。

You have to initial the array after you read the file and get the dimensions. 读取文件并获取尺寸后,必须初始化数组。 Try this: 尝试这个:

public static void main(String[] args) {
    int x, y;
    int[][] maze;
    try {
        Scanner reader = new Scanner(new File("C:\\Users\\User\\Desktop\\mazes\\input.txt"));
        x=reader.nextInt();
        y=reader.nextInt();
        maze = new int[x][y];
        for (int i=0; i<x; i++){
            for (int j=0; j<y; j++){
                maze[i][j]=reader.nextInt();
                System.out.println(maze[i][j]);
            }
        }       
        reader.close();
    } catch (FileNotFoundException e1) {
        System.out.println("Problem with the file");
        e1.printStackTrace();
    }
}

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

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