-2

I am having some issues understanding what Java wants syntactically for the program to work. The program is supposed to read the input file and then print out its contents. Once I do that, I will know how to manipulate its contents.

For example, my input file could look something like this:

1 2 3 
4 5 6
7 8 9 

This is my code:

import java.util.Scanner;
import java.io.*;

public class stats1 {

public static void main(String[] args) throws IOException {

Scanner s = new Scanner(new File("numbers.tex"));
int[][] numbers = new int[s.nextInt()][s.nextInt()];
for (int row = 0; row < numbers.length; row++)
    for(int col =0; col < numbers[row].length; col++)
      numbers[row][col]=s.nextInt(); 
      System.out.print(numbers[row][col] + " ");
  } 

}
4

1 回答 1

1

你需要一个{and}在第二个循环之后:

for (int row = 0; row < numbers.length; row++)
    for(int col =0; col < numbers[row].length; col++) {
      numbers[row][col]=s.nextInt(); 
      System.out.print(numbers[row][col] + " ");
    }

我建议您在外循环周围也使用大括号,以防止将来出现此类错误。

请注意,在您的情况下,numbers.length将为 1 和numbers[row].length2。(由于您声明并定义了数组,使用nextInt它从文件中获取了 1 和 2。

然后,您的循环将仅在 3 和 4 上运行。因此您的输出将是 3,4。

我建议你把矩阵的维度放在第一行。为了看到“矩阵形状”,您需要在内循环完成后打印一个空行。

或者,您可以先计算行数和列数,这样您就不需要在第一行添加维度。

于 2013-05-01T06:19:55.913 回答