我创建了一个带有随机文本的txt文件,该文件已输入到我的代码中。当我键入文件来运行它(它不是硬编码)时,它会不断给出我设置的错误。我该如何解决这个问题?
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class P7_5
{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Please enter file name: ");
String fileName = input.next();
File file = new File(fileName); //hard code file here
Scanner in = new Scanner(System.in);
try {
in = new Scanner(file);
} catch (FileNotFoundException e) {
System.out.println("File was not found!");
}
int numLines = 0;
int numWords = 0;
int numCharacters = 0;
while (in.hasNextLine()) {
String line = in.nextLine();
String[] words = line.split("\\s+");
numLines += 1;
numCharacters += line.length();
numWords = words.length;
}
in.close();
System.out.printf("Number of lines are: \n", numLines);
System.out.printf("Number of words are: \n", numWords);
System.out.printf("Number of characters are: \n", numCharacters);
}
}