【发布时间】:2020-11-09 02:11:43
【问题描述】:
我在尝试从用户那里获取输入时遇到了我的程序中的错误。基本上程序是什么,它是从两个不同的导出 txt 文件中提取数据,然后我将从每个文件中交叉引用。在这一点上,我只是想测试一下程序在交叉引用之前要收集的文件信息。
发生了什么,我读取了一个文件“FromFile.txt”,然后它会打印出所有内容,然后询问我们需要测试的另一个文件名是什么。此时,它会在第二次请求用户输入时抛出该错误。
我很难弄清楚为什么会引发错误
这是被抛出的错误。
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at CrossReferencingTool.getInputString(CrossReferencingTool.java:98)
at CrossReferencingTool.main(CrossReferencingTool.java:23)
下面是出现错误的代码。
public static String getInputString() {
Scanner input = new Scanner(System.in);
String string;
string = input.next(); <----------------- This is the line where it is throwing the error
input.close();
return string;
}
下面是正在运行的整体代码。
import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;
public class CrossReferencingTool {
public static void main(String[] args) throws FileNotFoundException {
ArrayList<ArrayList<String>> list1 = new ArrayList<ArrayList<String>>();
ArrayList<ArrayList<String>> list2 = new ArrayList<ArrayList<String>>();
System.out.println("What is the filename of the file you want to cross reference from:");
File file1 = new File(getInputString());
populateList(file1, list1);
printList(list1);
System.out.println("\nwhat is the filename of the file you want to cross reference with:");
File file2 = new File(getInputString());
populateList(file2, list2);
printList(list2);
}
private static void printList(ArrayList<ArrayList<String>> list) {
String row;
for(int x = 0; x < list.size(); x++) {
row = "";
for(int y = 0; y < list.get(x).size(); y++) {
row += list.get(x).get(y);
if( (y + 1) < (list.get(x).size())) {
row += ", ";
}
}
System.out.println(row);
}
}
private static void populateList(File file, ArrayList<ArrayList<String>> list) throws FileNotFoundException {
Scanner reader = new Scanner(file);
String splitLine[];
String line;
ArrayList<String> internalList;
while(reader.hasNextLine()) {
internalList = new ArrayList<String>();
line = reader.nextLine();
splitLine = line.split(",");
for(int x = 0; x < splitLine.length; x++) {
internalList.add(splitLine[x]);
}
list.add(internalList);
internalList = null;
}
reader.close();
}
public static String getInputString() {
Scanner input = new Scanner(System.in);
String string;
string = input.next();
input.close();
return string;
}
}
【问题讨论】:
标签: java file java.util.scanner