java - 用文件中的内容填充矩阵
问题描述
我的代码出现错误。目标是将文件的内容添加到矩阵中。然后我最终需要解析它以将其添加到图形中,以便我最终可以对其执行深度优先搜索。但在那之前我需要弄清楚这个错误。我无法弄清楚究竟是什么导致了错误。所以任何帮助都会很好。这是我得到的错误:
Exception in thread "AWT-EventQueue-0" java.util.NoSuchElementException
at java.base/java.util.Scanner.throwFor(Scanner.java:937)
at java.base/java.util.Scanner.next(Scanner.java:1478)
at DelivA.<init>(DelivA.java:53)
at Prog340.actionPerformed(Prog340.java:120
这是我写的课程。
public DelivA(File in, Graph gr) {
inputFile = in;
g = gr;
// Get output file name.
String inputFileName = inputFile.toString();
String baseFileName = inputFileName.substring(0, inputFileName.length() - 4); // Strip off ".txt"
String outputFileName = baseFileName.concat("_out.txt");
outputFile = new File(outputFileName);
if (outputFile.exists()) { // For retests
outputFile.delete();
}
try {
output = new PrintWriter(outputFile);
} catch (Exception x) {
System.err.format("Exception: %s%n", x);
System.exit(0);
}
// --------------------------------Deliverable
// A-------------------------------------------//
FileReader f1 = null;
int c = 0;
int r = 0;
try {
f1 = new FileReader(inputFileName);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Scanner scanner = new Scanner(f1);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
String splitLine[] = line.split(" ");
c = splitLine.length;
r++;
}
String[][] matrix = new String[c][r];
@SuppressWarnings("resource")
Scanner s1 = new Scanner(f1);
for (int row = 0; row < matrix.length; row++) {
String words = s1.next(); // will scan each row of the file
for (int col = 0; col < matrix[row].length; col++) {
char ch = words.charAt(col); // will put each character into array
matrix[row][col] = String.valueOf(ch);
}
}
}
}
解决方案
你的问题可能在这里:
String words = s1.next():
您没有验证是否有可用的线路。
你应该这样做:
...
Scanner s1 = new Scanner(f1);
for (int row = 0; row < matrix.length; row++) {
if (scanner.hasNextLine()){
String words = s1.next(); // will scan each row of the file
...
当然,您应该相应地重新考虑代码逻辑...
推荐阅读
- reactjs - 使用自定义“App”在 Next.js 中保留导航栏
- python - 使用 yolo 自定义损失函数训练神经网络的损失等于 nan?
- sql - 将 varchar 值 '' 转换为数据类型 Bit 时转换失败
- java - Java 正则表达式:模式和匹配器
- reactjs - REACTJS 错误:重新渲染太多。React 限制渲染次数以防止无限循环
- python - int分解成加法
- django - 没有名为roocket的模块
- docusignapi - 从一位专用用户发送信封
- java - 春季启动缓慢的jsp加载
- algorithm - 在二叉树中,对于每个节点,左右节点数之差