从文本文件创建2D数组

huangapple go评论81阅读模式
英文:

2D array from a text file

问题

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[i][j] = sr.nextInt();
                    System.out.print(storyGrid[i][j]);
                }
            }
        }
    }
}
英文:

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(&quot;C:\\Users\\Colton\\eclipseworkspace\\DoubleArray\\text.txt&quot;));
        {
            int a = 6;
            int b = 7;

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

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

</details>


# 答案1
**得分**: 1

你必须对要赋值的数组进行索引以便为该数组中的元素赋值示例
```java
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();

另外,请查看Java 数组教程

英文:

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 &lt; a; i++) {
    for (int j = 0; j &lt; b; j++) {
        storyGrid[i][j] = sr.nextInt();

Also checkout the java arrays tutorial

答案2

得分: 0

错误出在你的循环中,你试图直接将sr.NextInt()的值赋给一个数组类型,但我认为你想要赋值给矩阵的实际索引,所以只需将storyGrid = sr.nextInt();更改为:

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

我建议你查看一下这个关于数组的指南

英文:

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.

huangapple
  • 本文由 发表于 2020年8月31日 01:49:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/63660408.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定