从文本文件创建2D数组

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

2D array from a text file

问题

  1. import java.io.File;
  2. import java.io.FileNotFoundException;
  3. import java.util.Scanner;
  4. public class DoubleArray {
  5. public static void main(String args[]) throws FileNotFoundException {
  6. Scanner sr = new Scanner(new File("C:\\Users\\Colton\\eclipseworkspace\\DoubleArray\\text.txt"));
  7. {
  8. int a = 6;
  9. int b = 7;
  10. int[][] storyGrid = new int[a][b];
  11. sr.nextInt();
  12. for (int i = 0; i < a; i++) {
  13. for (int j = 0; j < b; j++) {
  14. storyGrid[i][j] = sr.nextInt();
  15. System.out.print(storyGrid[i][j]);
  16. }
  17. }
  18. }
  19. }
  20. }
英文:

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

  1. import java.io.File;
  2. import java.io.FileNotFoundException;
  3. import java.util.Scanner;
  4. public class DoubleArray {
  5. public static void main(String args[]) throws FileNotFoundException {
  6. Scanner sr = new Scanner(new
  7. File(&quot;C:\\Users\\Colton\\eclipseworkspace\\DoubleArray\\text.txt&quot;));
  8. {
  9. int a = 6;
  10. int b = 7;
  11. int[][] storyGrid = new int[a][b];
  12. sr.nextInt();
  13. for (int i = 0; i &lt; a; i++) {
  14. for (int j = 0; j &lt; b; j++) {
  15. storyGrid = sr.nextInt();
  16. System.out.print(storyGrid[i][j]);
  17. }
  18. }
  19. }
  20. }
  21. }
  22. </details>
  23. # 答案1
  24. **得分**: 1
  25. 你必须对要赋值的数组进行索引以便为该数组中的元素赋值示例
  26. ```java
  27. int[][] storyGrid = new int[a][b];
  28. sr.nextInt();
  29. for (int i = 0; i < a; i++) {
  30. for (int j = 0; j < b; j++) {
  31. 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:

  1. int[][] storyGrid = new int[a][b];
  2. sr.nextInt();
  3. for (int i = 0; i &lt; a; i++) {
  4. for (int j = 0; j &lt; b; j++) {
  5. storyGrid[i][j] = sr.nextInt();

Also checkout the java arrays tutorial

答案2

得分: 0

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

  1. 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:

  1. 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:

确定