Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Unknown Source)
at LineIO.main(LineIO.java:39)
没有红线。我会发布代码......
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
public class LineIO {
public static void main(String[] args)throws FileNotFoundException{
Scanner console = new Scanner(System.in);
System.out.print("Enter Input file name: ");
String inputFileName = console.next();
System.out.print("Output file: ");
String outputFileName = console.next();
File inputFile = new File(inputFileName);
Scanner in = new Scanner(inputFile);
PrintWriter out = new PrintWriter(outputFileName);
int lineNumber = 1;
int lineNumber2 = 10;
int lineNumber3 = 20;
int lineNumber4 = 30;
int lineNumber5 = 40;
System.out.println("Enter name 5 names:");
String person1 = console.next();
String person2 = console.next();
String person3 = console.next();
String person4 = console.next();
String person5 = console.next();
double sum = 0;
int j = 0;
while (j < 10)
{
String line = in.nextLine();
int num = Integer.parseInt(line);
sum = sum+num;
}
double average = sum / 10;
System.out.println(person1 + " average score is " + average);
System.out.println(person2 + " average score is " + lineNumber2);
System.out.println(person3 + " average score is " + lineNumber3);
System.out.println(person4 + " average score is " + lineNumber4);
System.out.println(person5 + " average score is " + lineNumber5);
in.close();
out.close();
}
}
为什么我会继续收到此错误?我无法理解错误消息,也不明白为什么代码没有实现。我设置了input.txt和output.txt文件......
答案 0 :(得分:2)
快速搜索了这篇文章:java.util.NoSuchElementException: No line found
文件中没有足够的行。
除了确保文件中有足够的行外,还要添加下一行的检查以避免此错误:
while (j < 10)
{
if (in.hasNextLine()){
String line = in.nextLine();
int num = Integer.parseInt(line);
sum += num; //minor change here
}
else{
System.out.println("Not enough lines!");
break;
}
j++; //increment j
}