【问题标题】:Turning a TextIO file into a vector (array) which it then returns将 TextIO 文件转换为向量(数组),然后返回
【发布时间】:2016-01-31 09:05:59
【问题描述】:

我正在尝试编写一个家庭作业程序,该程序打开一个由字符串给出的文件,并将一系列逗号分隔的整数值读入一个数组,然后返回。

import java.util.Arrays;

...

int[] readVector(String filename) throws IOException {
    File f = new File(filename);

    FileOutputStream fos = new FileOutputStream(f, true);

    PrintWriter pw = new PrintWriter(fos);
    pw.println("");
    pw.close();

    FileReader fr = new FileReader(f);
    BufferedReader bfr = new BufferedReader(fr);
    while (true) {
        String s = bfr.readLine();
        if (s == null) {
            break;
        }
        System.out.println(s);
    }
    bfr.close();;

    return NOIDEA;
}

考虑一下...

Matrix m = new Matrix();
System.out.println(Arrays.toString(m.readVector("vector.txt"))); // print "[1, 2, 3, 4]"

【问题讨论】:

  • .......你的具体问题是?
  • 抱歉,我想知道如何将文本文件转换为矢量。不知道如何做到这一点

标签: java arrays matrix type-conversion


【解决方案1】:

将文件内容读入一个数组,然后使用这个进行转换:

Vector<Integer> returnVec = new Vector(Arrays.asList(YOUR_ARRAY));

如果您在将文本文件读入数组时遇到问题,请查看this question

【讨论】:

  • 我唯一的问题是return语句需要是一个int数组。
  • 完美。在这种情况下,只需返回原始数组。所以这里是给你一个想法的流程:首先,将文件中的所有整数读入一个数组。如果这就是您需要做的所有事情,请查看我的答案中的链接。如果您随后需要将其转换为向量,请使用我提供的语法。当您完成任何操作时,只需返回原始整数数组。
【解决方案2】:

根据您的描述, 你的实现包含很多它并不真正需要的东西, 例如FileOutputStreamPrintWriter。 如果这些值在一行上, 那么处理一行就足够了, 使用Scanner 很容易做到这一点。

应该这样做:

int[] readVector(String filename) throws IOException {
    return Arrays.stream(new Scanner(new File(filename)).nextLine().split(","))
           .mapToInt(Integer::parseInt).toArray();
}

【讨论】:

    猜你喜欢
    • 2017-04-14
    • 2020-12-18
    • 2012-02-02
    • 1970-01-01
    • 2011-03-07
    • 2014-08-24
    • 2011-04-24
    • 1970-01-01
    • 2016-06-22
    相关资源
    最近更新 更多