我正在编写一个使用方法将.txt文件读入String数组的程序。但是,当我尝试通过在主程序中打印数组来测试我的方法时,什么也没有发生。我创建了一种将txt文件读入数组的方法,现在我试图在主程序中打印该数组以确保其正常工作。
感谢所有帮助,这是我的代码:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.Scanner;
public class P4Test {
public static void main(String[] args) throws FileNotFoundException {
// have user enter name for file
Scanner input = new Scanner(System.in);
System.out.println("Enter the name of the file");
String nameOfFile = input.nextLine();
String[] test = readFile(nameOfFile);
System.out.println(Arrays.toString(test));
}
public static String[] readFile(String filename) throws FileNotFoundException
{
//read the file
Scanner file = new Scanner(new File(filename));
// read number of lines inside file
int numString = 0;
while (file.hasNextLine());
{
++numString;
file.nextLine();
}
file.close();
// now we read the file into a string array
Scanner keyboard = new Scanner(new File(filename));
String[] words = new String[numString];
// using a for loop to read in each line to the array
for (int index = 0; index < numString; ++index) {
words[index] = keyboard.nextLine();
}
keyboard.close();
return words;
}
}
答案 0 :(得分:0)
您的代码非常好,除了以下行:
while (file.hasNextLine());
您需要从while循环中删除该分号。