繁体   English   中英

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

[英]Storing integers from file to 2D array

我正在尝试类似导入

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

文件进入2D数组,但是我很难过,这是到目前为止的代码,什么都不做,没有语法错误,所以除了空白的控制台之外我没有任何错误,我也不知道我做了什么错误。 数组的大小是文件中的前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();
    }
}}

您以大小为0的数组作为初始数组。因此,此处不会再有其他内容。

读取文件并获取尺寸后,必须初始化数组。 尝试这个:

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