简体   繁体   English

来自文本文件的二维数组

[英]2D array from a text file

I have been trying to get this figured out.我一直试图弄清楚这一点。 When I am putting in the code, I am getting an error from the storyGrid = sr.nextInt();当我输入代码时,我从storyGrid = sr.nextInt();收到错误storyGrid = sr.nextInt();

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class DoubleArray {
    public static void main(String args[]) throws FileNotFoundException {
        Scanner sr = new Scanner(new
            File("C:\\Users\\Colton\\eclipseworkspace\\DoubleArray\\text.txt"));
        {
            int a = 6;
            int b = 7;

            int[][] storyGrid = new int[a][b];

            sr.nextInt();
            for (int i = 0; i < a; i++) {
                for (int j = 0; j < b; j++) {
                    storyGrid = sr.nextInt();
                    System.out.print(storyGrid[i][j]);
                }
            }
        }
    }
}

You have to index the array you are referencing to assign a value to an element in that array, example:您必须索引要引用的数组才能为该数组中的元素赋值,例如:

int[][] storyGrid = new int[a][b];

sr.nextInt();
for (int i = 0; i < a; i++) {
    for (int j = 0; j < b; j++) {
        storyGrid[i][j] = sr.nextInt();

Also checkout the java arrays tutorial还可以查看java arrays 教程

The error it's in your foor loop, your trying to assign the value of sr.NextInt() directly to an Array type , when I think you want to assign to the actual index of the Matrix so just change storyGrid = sr.nextInt();错误是在您的 for 循环中,您尝试将sr.NextInt()的值直接分配给Array 类型,当我认为您想分配给 Matrix 的实际索引时,只需更改storyGrid = sr.nextInt(); to:到:

storyGrid[i][j] = sr.nextInt();

I can suggest you to take a look to this guide about arrays .我可以建议你看看这个关于数组的指南

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

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