我在使用 OOP 读取 java 中的第一行数据时遇到一些问题。这里无需 OOP 即可工作:
Scanner in = new Scanner(System.in); // sets up scanner
System.out.print("Enter file name: "); //user provides file name and location
String userFile = in.nextLine(); // accepts input from user
File file = new File(userFile); //uses the file method to import the data
Scanner inputFile = new Scanner(file); // uses scanner to read the data
String fileContents = inputFile.nextLine();
System.out.print(fileContents);
但是我无法让它在类文件中工作,因为方法 nextLine() 对于 String 类型是未定义的,即使我实际上只是在上面使用了它。
public String Out(String userIn)
{
String nOfStudentsIndex = userIn.nextLine();
另外为什么我不能以这种方式将文件传递给另一个类文件?
Scanner in = new Scanner(System.in); // sets up scanner
System.out.print("Enter file name: "); //user provides file name and location
String userFile = in.nextLine(); // accepts input from user
File file = new File(userFile); //uses the file method to import the data
Scanner inputFile = new Scanner(file); // uses scanner to read the data
System.out.println(inputFile.Out());
最佳答案
为什么不在需要的地方传入 Scanner 对象呢?例如,
// pass in Scanner, not String
public String Out(Scanner userIn) {
String nOfStudentsIndex = userIn.nextLine();
请确保不要关闭使用 System.in
的扫描程序,直到您的程序明确使用它为止。
另外,这行不通:
Scanner inputFile = new Scanner(file); // uses scanner to read the data
System.out.println(inputFile.Out());
as Scanner 没有 Out()
方法。根据 Scanner API,您只能使用该类可用的方法。
您可以使用扫描仪解析文件,并使用 while 循环打印出每一行
Scanner fileScan = new Scanner(file); // uses scanner to read the data
while (fileScan.hasNextLine()) {
System.out.println(fileScan.nextLine();
}
fileScan.close();
关于java - OOP 文件读取问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33880897/