java - 可以从一个文件创建两个不同大小的数组/矩阵吗?

标签 java matrix multidimensional-array

基本上,我正在尝试从如下所示的文本文件创建两个不同大小的二维数组:

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 是问题数量(加法和减法),34 是行数和列数,以及下面的数字是填充到二维数组中的两个单独的矩阵。如果我就停在那里,这个程序就可以正常工作:

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

    }
}

它可以很好地创建和打印矩阵,没有任何问题。但是,每当我尝试创建并打印接下来的两个矩阵(下面的 2x2 数组在文本文件中相减)时,它都会返回以下错误:

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?

最佳答案

我建议将您的实现分解为以下部分:

  • class Matrix - 保存问题定义中的一个矩阵的值
  • class Problem - 保存问题定义中的运算和两个矩阵

Matrix 类可能如下所示:

class Matrix {
    private int[][] values;

    public Matrix(int[][] values) {
        this.values = values;
    }

    public int[][] getValues() {
        return values;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("Matrix [values=\n");
        for (int i = 0; i < values.length; i++) {
            sb.append("\t" +  Arrays.toString(values[i]) + "\n");
        }
        sb.append("]");
        return sb.toString();
    }
}

问题类可能是:

class Problem {
    private String operation;
    private Matrix first;
    private Matrix second;

    public Problem(String operation, Matrix firstMatrix, Matrix secondMatrix) {
        this.operation = operation;
        first = firstMatrix;
        second = secondMatrix;
    }

    public String getOperation() {
        return operation;
    }

    public Matrix getFirst() {
        return first;
    }

    public Matrix getSecond() {
        return second;
    }

    @Override
    public String toString() {
        return "Problem [\noperation=" + operation + ", \nfirst=" + first + ", \nsecond=" + second + "\n]";
    }
}

基于此,您的“驱动程序”类执行以下操作:

  1. 从用户输入中获取文件名
  2. 从文件中读取问题数量并以此初始大小构建一个列表
  3. 对于问题的数量(即 2),获取操作、行和列,并构造一个包含这些信息的新 Problem 对象,并将 Problem 放入列表中...

这是一个简单的解决方案 - 这里仍有改进的空间:-)

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;

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

         List<Problem> problems = readProblems(filename);
         System.out.println(problems);
         keyboard.close();
    }

    private static List<Problem> readProblems(final String filename) throws FileNotFoundException {
        Scanner fileReader = new Scanner(new FileInputStream(filename));
        int numberOfProblems = fileReader.nextInt();
        List<Problem> problems = new ArrayList<>(numberOfProblems);
        for (int i = 1; i <= numberOfProblems; i++) {
            problems.add(readProblem(fileReader));
        }
        fileReader.close();
        return problems;
    }

    private static Problem readProblem(Scanner fileReader) throws FileNotFoundException {
        fileReader.nextLine(); // go to next line
        String operation = fileReader.nextLine(); // read problem operation
        int rows = fileReader.nextInt(); // read number of rows 
        int columns = fileReader.nextInt(); // read number of columns
        Matrix firstMatrix = readMatrix(rows, columns, fileReader);
        Matrix secondMatrix = readMatrix(rows, columns, fileReader);
        return new Problem(operation, firstMatrix, secondMatrix);
    }

    private static Matrix readMatrix(final int rows, final int columns, final Scanner fileReader) 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 new Matrix(result);
    }

}

使用您的输入文件进行测试。

HTH

关于java - 可以从一个文件创建两个不同大小的数组/矩阵吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41812145/

相关文章:

java 多维数组失败并出现空指针异常

c - 通过指针从动态分配的二维数组中获取值

java - 同一虚拟机中不同应用程序之间的通信

arrays - 二维数组扩展 Swift 3.1.1

java - 如何使用 maven mvn test 命令行运行动态 testng.xml?

javascript - 如何将鼠标移动距离转换为 SVG 坐标空间?

c++ - 在 C++ 中使用 vector 的矩阵运算导致段错误

java - 计算矩阵平方行列式

java - 如何将对象存储到 Android 中的 SQLite 数据库中?

java - 如何在运行时设置 JTextField 的宽度?