【问题标题】:How to create a file that write the result of multiplication of two 2-D arrays?如何创建一个写入两个二维数组相乘结果的文件?
【发布时间】:2012-01-28 20:33:30
【问题描述】:

我读过一个问题,要求编写一个执行以下操作的程序:

  • 从两个文件中读取两个不同的矩阵。一个是 3x4 矩阵,另一个是 4x3。
  • 将这两个矩阵相乘的结果写入文件。
    我初始化了所需的数组,如下所示:
    int [][] m1 = new int [3][4];
    int [][] m2 = new int [4][3];
    int [][] m3 = new int [3][3];
    

    我编写了打开两个输入文件所需的代码

    Scanner input1 = null;
    Scanner input2 = null;
    
    PrinWriter output = null;
    
    // first file
    try {
        Scanner input1 = new Scanner(new FileInputStream("file1.txt"));
    } catch (Exception e) {
        System.out.println("The file cannot be open");
    }
    
    // second file
    try {
        Scanner input2 = new Scanner (new FileInputStream("file2.txt"));
    } catch (Exception e){
        System.out.println("The File Cannot be open");
    }
    

    但是后来我无法处理 try & catch 事情以及如何读取我需要操作的两个文件的内容以便将它们写入结果文件

  • 【问题讨论】:

    • 你的意思是你不能处理 try-catch 的事情?你哪里有困难?
    • Exception 是一个非常抽象的 IO 异常,你需要 IOException。如果您收到异常但不知道详细信息,请尝试打印堆栈跟踪:e.printStackTrace();

    标签: java arrays io console try-catch


    【解决方案1】:

    您需要在 try/catch 中执行文件 IO,但您可能缺少的是,当您从文件中读取值时,您可以填充应该在 try/catch 范围之外定义的数组。

    int[][] array1 = ...;
    int[][] array2 = ...;
    
     try{
         // read file 1 and populate array 1
     catch(IOException e){
         // log failure here, possibly exit application
     }
     try{
         // read file 2 and populate array 2
     catch(IOException e){
         // log failure here, possibly exit application
     }
    
      // do array arithmetic
    
     try{
         // write output file file
     catch(IOException e){
         // log failure here, possibly exit application
     }
    

    【讨论】:

      猜你喜欢
      • 2013-09-21
      • 2014-04-03
      • 2017-09-13
      • 2017-08-13
      • 1970-01-01
      • 1970-01-01
      • 2014-03-05
      • 1970-01-01
      • 2021-08-15
      相关资源
      最近更新 更多