简体   繁体   中英

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();

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

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(); to:

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

I can suggest you to take a look to this guide about arrays .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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