从文件Java获取矩阵

如何解决从文件Java获取矩阵

我目前有一个格式为

的文本文件
matrix
row
a
b
c
row
d
e
f
row
g
h
i
row
j
k
l
matrix
row
m
n
o
p
q
row
r
s
t
u
v

我想将此格式转换为两个整数矩阵(存储为2个2D数组)

a b c

d e f

g h i

j k l

m n o p q

r s t u v

到目前为止,我已经创建了文件的Scanner对象,并将每一行放入文本数组:

Scanner sf = new Scanner(new File("C:\\textfiles\\matrices.txt"));
int maxIndex = -1;
String text[] = new String[10000]; // I added more than necessary for safety
while (sf.hasNext()){
    maxIndex++;
    text[maxIndex] = sf.nextLine();
}
sf.close();

这样,文本文件现在包含在字符串数组中,其中每一行都是该数组的新元素。现在,我想将数组划分为两个数组,每个数组都是矩阵。我应该如何继续? (注意:我是一个总的初学者,希望得到简单的答案(没有arraylist,hashmap等),这就是为什么这个问题不是How to read two matrices from a txt file in java的重复,因为它使用了BufferedReader,并且还有其他潜在的重复问题,所以我想澄清一下)

目前我排在榜首之后的是

int counter = 0;
int iCounter = 0; // row
int jCounter = 0; // column

int matrix1[][];
int matrix2[][];
while (counter < maxIndex){
    if (counter = 0)
    {
        \\not yet written...
    }
    \\not yet written...
}

解决方法

这就是您想要的。不幸的是,使用二维数组很难做到这一点,因为一旦设置了数组的大小,就很难改变它。因此,使用ArrayList容易得多。

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

class Main {

    public static final String MATRIX = "matrix";
    public static final String ROW = "row";

    public static void main(String[] args) throws FileNotFoundException {
        // Use correct file name here
        Scanner sf = new Scanner(new File("matrices.txt"));

        // This is a List of 2D Lists
        List<List<List<String>>> matrices = new ArrayList<>();

        // easier to process lines as we're reading them in so we
        // only iterate over the file once
        while (sf.hasNext()) {
            boolean hasBeenProcessed = false;

            String inputValue = sf.nextLine();

            switch (inputValue) {
                case MATRIX:
                    ArrayList<List<String>> matrix = new ArrayList<>();
                    matrices.add(matrix);
                    hasBeenProcessed = true;
                    break;
                case ROW:
                    List<List<String>> currentMatrix = getMatrixBeingProcessed(matrices);
                    currentMatrix.add(new ArrayList<String>());
                    hasBeenProcessed = true;
                    break;
            }
            if (!hasBeenProcessed) {
                List<List<String>> currentMatrix = getMatrixBeingProcessed(matrices);
                List<String> currentRow = getCurrentRow(currentMatrix);
                currentRow.add(inputValue);
            }
        }

        // Print out the results:
        int i = 1;
        for (List<List<String>> matrix : matrices) {
            System.out.println("Matrix " + i);
            for (List<String> row : matrix) {
                for (String element : row) {
                    System.out.print(element + " "); // no newline until end of the row
                }
                System.out.println(); // new line
            }
            i++;
            System.out.println(); // new line
        }
    }

    private static List<String> getCurrentRow(List<List<String>> currentMatrix) {
        int lastRow = currentMatrix.size() - 1;
        return currentMatrix.get(lastRow);
    }

    private static List<List<String>> getMatrixBeingProcessed(List<List<List<String>>> matrices) {
        int lastMatrix = matrices.size() - 1;
        List<List<String>> currentMatrix = matrices.get(lastMatrix);
        return currentMatrix;
    }
}

输出:

Matrix 1
a b c 
d e f 
g h i 
j k l 

Matrix 2
m n o p q 
r s t u v 


Process finished with exit code 0
,

正如@Rob所说的,如果没有诸如ArrayList这样的动态数据结构,这样做确实很麻烦。但是,尽管如此,这是一个可以完成您的工作的代码(考虑到您只有两个矩阵),而无需使用任何List:

int counter = 0;
int iCounter = 0; // row
int jCounter = 0; // column
int matrix1[][];
int matrix2[][];

int rowSize = 0,numberOfRows = 0;
counter = 2;
while (!text[counter].equals("row") && !text[counter].equals("matrix")) {
  counter++;
  rowSize++;
}

//now we have the row size
numberOfRows = 1;
while (!text[counter].equals("matrix")) {
  if (text[counter].equals("row"))
    numberOfRows++;
  counter++;
}
//now we have the total number of rows
matrix1 = new int[numberOfRows][rowSize];

counter = 2;  //to start from the first matrix
//now counter should point to the first row of the first matrix
while (!text[counter].equals("matrix")) {
  jCounter = 0;
  while (!text[counter].equals("row")
         && !text[counter].equals("matrix")) {
    matrix1[iCounter][jCounter++] = Integer.parseInt(text[counter]);
    //supposing your input is Integers,otherwise,you can change
    //it to the corresponding type (i.e. Long,Double,etc)
    counter++;
  }
  iCounter++;
  if (!text[counter].equals("matrix"))
    counter++;
}
//now we finished with the first matrix,and the counter points to
//the first "row" of the second matrix,so we do the same thing again
rowSize = 0;
numberOfRows = 0;
int startOfSecondMatrix = counter + 2;  //save this for later
counter += 2;  // so that counter points to the first number
while (counter < text.length && !text[counter].equals("row")) {
  counter++;
  rowSize++;
}
numberOfRows = 1;
while (counter < text.length) {
  if (text[counter].equals("row"))
    numberOfRows++;
  counter++;
}
matrix2 = new int[numberOfRows][rowSize];

counter = startOfSecondMatrix;
iCounter = 0;
while (counter < text.length) {
  jCounter = 0;
  while (counter < text.length && !text[counter].equals("row")) {
    matrix2[iCounter][jCounter++] = Integer.parseInt(text[counter]);
    counter++;
  }
  iCounter++;
  counter++;
}

对于每个矩阵,我们执行相同的操作: -我们首先浏览矩阵以计算其大小以进行初始化,然后逐行分析每个数字。
您也可以将一个矩阵的所有工作放到一个函数中(并注意边界),并在您还有更多矩阵的情况下调用它。

,

由于您不想使用列表,并且一旦初始化就无法调整数组的大小,所以这并不容易。

有两种方法:读取文件并初始化数组,知道其大小(如@Maaddy发布)或“调整大小”数组。这是不可能的,但是如果您使用Arrays.copyOf(),则可以创建一个新数组。

这个想法是创建一个“三维”数组,您可以在其中存储:矩阵,行和列;然后开始读取文件。 每次找到一个单词时,整个数组都会更新,从而创建一个长度增加一个新数组。

如果单词是“矩阵”,则多余的长度将添加到第一个位置(“存储”矩阵的位置)

如果单词是“ row”,那么将为当前矩阵添加空格。因此,以这种方式,当前矩阵将再有一个数组,用于存储列值。

如果单词为other,则为该列的值。调整列的大小并将其添加到正确的位置。

请注意,如果找到单词“ matrix”或“ row”,则新数组将初始化为没有长度的数组。这是因为稍后将在必要时调整大小。

代码如下:

//Initialize array with no positions
String[][][] arrays = new String[0][0][0];
Scanner sf = new Scanner(new File("path/matrices.txt"));
int matrix = -1;
int row = -1;
int column = -1;
while (sf.hasNext()){
    String line = sf.nextLine();
    if(line.equals("matrix")) {
        //'Resize' array: Create new array with 1 more length and old data
        arrays = Arrays.copyOf(arrays,arrays.length + 1);
        //Start new matrix
        arrays[++matrix] = new String[0][0];
        row = -1;
        column = -1;
    }else if(line.equals("row")) {
        //'Resize' matrix: Create a new array with 1 more length and old data
        arrays[matrix] = Arrays.copyOf(arrays[matrix],arrays[matrix].length+1);
        row++;
        arrays[matrix][row] = new String[0];
        column = -1;
    }else{
        //'Resize' matrix
        column++;
        arrays[matrix][row] = Arrays.copyOf(arrays[matrix][row],arrays[matrix][row].length+1);
        arrays[matrix][row][column] = line;
    }
}
sf.close();

//Print result
for(int i = 0 ; i < arrays.length; i++) {
    System.out.println("Matrix "+i);
    for(int j = 0; j < arrays[i].length; j++ ) {
        for(int k = 0; k < arrays[i][j].length; k++) {
            System.out.print(arrays[i][j][k]+ " ");
        }
        System.out.println();
    }
    System.out.println();
}   

结果是:

Matrix 0
a b c 
d e f 
g h i 
j k l 

Matrix 1
m n o p q 
r s t u v 

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-