【问题标题】:One-line Java scanner to read a matrix from a file用于从文件中读取矩阵的单行 Java 扫描器
【发布时间】:2015-03-11 11:31:51
【问题描述】:

我一直在用这个;一种单线:

public static String[] ReadFileToStringArray(String ReadThisFile) throws FileNotFoundException{
    return (new Scanner( new File(ReadThisFile) ).useDelimiter("\\A").next()).split("[\\r\\n]+");
}

读取具有此类内容的文件(即带有字符串标记):

abcd
abbd
数据库光盘

但是,现在我的文件内容是这样的:

1 2 3 4
1 2 2 4
1 5 3 7
1 7 3 8

我希望将这些值读取为整数。

我已经看到这些123 问题,但它们没有回答我的问题。

我尝试了以下方法但失败了:

public static int[][] ReadFileToMatrix(String ReadThisFile) throws FileNotFoundException{
    return (new Scanner( new File(ReadThisFile) ).useDelimiter("\\A").nextInt()).split("[\\r\\n]+");
}

错误消息: 无法在基本类型 int 上调用 split(String) 我理解该消息并且知道它非常错误:)

任何人都可以提出正确的方法来实现这一点。

附:恕我直言,对带有循环的解决方案说“不”。

【问题讨论】:

  • 很容易将数字读取为ints 并将它们存储在一维数组中。但是我想不出没有循环将一维数组转换为二维的方法。或者至少是递归..
  • 根据 Java 约定,变量 (readThisFile) 和方法名 (readFileToMatrix) 以小写字母开头。
  • 您可以在 Google 上搜索“Java 命名约定”,但这里有一个简短的说明:en.wikipedia.org/wiki/Naming_convention_%28programming%29#Java

标签: java arrays string int java.util.scanner


【解决方案1】:

当基本的BufferedReaderInteger.parseInt(line.split(" ")[n]); 可以使用时,使用类似乎过于复杂。

【讨论】:

  • 您能写下完整的行吗? return之后会怎样?
  • 不在一行中。为什么你需要它在一条线上?
【解决方案2】:

如果您使用 Java 7 或更高版本,则可以使用类似的东西。我想不出一种方法可以在没有循环的情况下在一行中完成。只需将其放入方法中并调用它即可。

//Read full file content in lines
List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);

int NR_OF_COLUMNS = 4;
int NR_OF_ROWS = lines.size();

int[][] result = new int[NR_OF_ROWS][NR_OF_COLUMNS];

for(int rowIndex = 0; rowIndex < NR_OF_ROWS; rowIndex++)
{
    String[] tokens = lines.get(rowIndex).split("\\s+");  //split every line
    for(int columnIndex = 0; columnIndex < NR_OF_COLUMNS; columnIndex++)
        result[rowIndex][columnIndex] = Integer.parseInt(tokens[columnIndex]);   //convert every token to an integer
}
return result;

【讨论】:

    【解决方案3】:

    在 Java 8 中,您可以使用 Lambda:

    public static int[][] readFileToMatrix(String readThisFile) throws FileNotFoundException{
        return Arrays.stream((new Scanner( new File(readThisFile) ).useDelimiter("\\A").nextInt()).split("[\\r\\n]+")).mapToInt(Integer::parseInt).toArray();
    }
    

    否则你不能在没有循环的情况下做到这一点。你有一个String[] 数组,你想为每个元素一个接一个地调用Integer.parseInt()

    【讨论】:

    • 看起来不错,能否请您添加有关如何映射的详细信息,然后将其作为int 2D 数组返回。
    猜你喜欢
    • 2011-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多