基本上,我試圖從看起來像這樣的文本文件創建兩個不同大小的二維數組:可能從文件創建兩個不同大小的數組/矩陣?
2
add
3 4
2 1 7 -10
0 5 -3 12
1 7 -2 -5
0 1 2 3
4 5 6 7
8 9 0 1
subtract
2 2
2 12
10 0
4 6
9 1
的2
是(增加和減少)的問題數,3
和4
是行數和列數,以及它下面的數字是兩個單獨的矩陣被填充到二維數組中。如果我只是停在那裏,這個程序正常工作:
class Matrices {
private Scanner fileReader;
private int rows;
private int columns;
int problems;
String method;
public Matrices(String file) throws FileNotFoundException {
this.fileReader = new Scanner(new FileInputStream(file));
problems = fileReader.nextInt();
method = fileReader.next();
if(method.equals("add")) {
rows = fileReader.nextInt();
columns = fileReader.nextInt();
}
}
public int[][] readMatrix() throws FileNotFoundException {
int[][] result = new int[rows][columns];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
result[i][j] = fileReader.nextInt();
}
}
return result;
}
public int[][] add(int[][] a, int[][] b) {
int[][] result = new int[rows][columns];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
result[i][j] = a[i][j] + b[i][j];
}
}
return result;
}
public void printMatrix(int[][] matrix) {
for (int[] anArray : matrix) {
for (int anInt : anArray) {
System.out.print(anInt+ " ");
}
System.out.println();
}
}
}
有了這個驅動程序:
public class MatricesDriver {
public static void main(String[] args) throws FileNotFoundException {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter name of file: ");
String filename = keyboard.next();
Matrices matrixReader = new Matrices(filename);
int[][] a = matrixReader.readMatrix();
int[][] b = matrixReader.readMatrix();
System.out.println("Matrix 1: ");
matrixReader.printMatrix(a);
System.out.println();
System.out.println("Matrix 2: ");
matrixReader.printMatrix(b);
System.out.println();
System.out.println("Addition: ");
int[][] addition = matrixReader.add(a,b);
matrixReader.printMatrix(addition);
}
}
它創建和打印矩陣得很好,沒有任何問題。然而,每當我試圖創建和打印接下來的兩個矩陣(下面的文本文件減去2×2陣列),它返回以下錯誤:
Enter name of file:
data/Matrices.txt
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at baker.Matrices.readMatrix(Matrices.java:27)
at baker.MatricesDriver.main(MatricesDriver.java:15
我的問題是,我應該做出什麼樣的調整,以使程序認識到2D陣列中的兩個是3x4,以下兩個是2x2?
是給出的文本格式? – swinkler
該文本文件?是的,就像它在那裏列出的一樣,沒有空格,也沒有單獨的文件 – bgb102
沒有空格我的意思是沒有空格之間的空格,對不明確的道歉 – bgb102