gpt4 book ai didi

java - 从文件读取到java中的 boolean 矩阵

转载 作者:行者123 更新时间:2023-12-01 22:28:02 24 4
gpt4 key购买 nike

我有一个格式如下的文本文件:

5
true, false, true, false, false
true, false, true, true, true
false, false, false, false, true
true, true, false, true, true
false, false, false, true, false

我想将其读入矩阵。这是我到目前为止所做的事情:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;

public class tests {

public static void main(String[] args) throws IOException {

System.out.println("File Name: ");
Scanner reader = new Scanner(System.in);
String fileName = reader.nextLine();
Scanner file = new Scanner(new BufferedReader(new FileReader(fileName)));

int size = file.nextInt();

System.out.println("Size: " + size);

boolean[][] matrix = new boolean[size][size];


for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {

matrix[i][j] = file.nextBoolean();
}

}
reader.close();
file.close();
}
}

但是这给了我一个错误:

    Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:864)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextBoolean(Scanner.java:1782)
at tests.tests.main(tests.java:27)

关于如何解决这个问题有什么想法吗?

最佳答案

在从下一行读取之前,您必须先读取行尾字符:

    int size = file.nextInt();
file.nextLine(); // added
System.out.println("Size: " + size);

boolean[][] matrix = new boolean[size][size];
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
matrix[i][j] = file.nextBoolean();
}
file.nextLine(); // added
}

关于java - 从文件读取到java中的 boolean 矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28366472/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com