主线程java.util.NoSuchElementException中的异常
我正在做这个项目来提高我的Java技能。我的目标是编写一个程序,从指定的文档或文本文件中读取行(取决于用户想要打开的文件;分别为int 2或int 1),然后要求用户输入其文档名(不带文件扩展名),然后读取文档或文本文件中的第一行。我希望它可以根据用户的需要多次这样做。但在执行代码时,我一直得到主线程java.util.NoSuchElementException中的异常,java,Java,我正在做这个项目来提高我的Java技能。我的目标是编写一个程序,从指定的文档或文本文件中读取行(取决于用户想要打开的文件;分别为int 2或int 1),然后要求用户输入其文档名(不带文件扩展名),然后读取文档或文本文件中的第一行。我希望它可以根据用户的需要多次这样做。但在执行代码时,我一直得到无接触异常 public class switches { public static void main(String[] args) throws IOException {
无接触异常
public class switches {
public static void main(String[] args) throws IOException {
Scanner input = new Scanner(System.in);
System.out.println("How many files would you like to scan?");
System.out.println("Enter # of files to scan: ");
int countInput = input.nextInt();
input.close();
for (int count = 0; count < countInput;) {
System.out.println("Please enter a file name to scan. ");
System.out.println("1 for .txt, 2 for .doc");
Scanner keyboard = new Scanner(System.in);
int choice = keyboard.nextInt();
switch (choice) {
default: {
do {
System.out.println("Please pick "
+ "either 1: txt or 2: doc");
choice = keyboard.nextInt();
} while (choice != 1 && choice != 2);
}
case 1: {
System.out.println("Txt file name:");
keyboard.nextLine();
String txtName = keyboard.nextLine();
File openTxtFile = new File("C:/Users/Hp/Documents/" + txtName
+ ".txt");
Scanner firstTxtLine = new Scanner(openTxtFile);
String printedTxtLine = firstTxtLine.nextLine();
firstTxtLine.close();
System.out.println("The first line " + "of your text file is: "
+ printedTxtLine);
keyboard.close();
count++;
break;
}
case 2: {
System.out.println("Doc file name:");
keyboard.nextLine();
String docName = keyboard.nextLine();
File openDocFile = new File("C:/Users/Hp/Documents/" + docName
+ ".doc");
Scanner firstLine = new Scanner(openDocFile);
String printedDocLine = firstLine.nextLine();
firstLine.close();
System.out.println("The first line"
+ " of your word document is: " + printedDocLine);
keyboard.close();
count++;
break;
}
}
}
}
}
公共类交换机{
公共静态void main(字符串[]args)引发IOException{
扫描仪输入=新扫描仪(System.in);
System.out.println(“您希望扫描多少文件?”);
System.out.println(“输入要扫描的文件的数量:”;
int countInput=input.nextInt();
input.close();
对于(int count=0;count
如果删除行input.close()代码>在第14行。这应该能解决你的问题。根据,它将抛出一个NoTouchElementException
-“如果输入已耗尽”。异常具体发生在哪里?