英文:
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("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]);
}
}
}
}
}
</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 < a; i++) {
for (int j = 0; j < 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论