[英]Why is my array returned by a method not printing to console?
我正在编写一个程序,它将 a.txt 文件读入一个使用方法的字符串数组。 但是,当我尝试通过在主程序中打印数组来测试我的方法时,什么也没有发生。 我创建了一个将 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;
}
}
您的代码非常好,除了这一行:
while (file.hasNextLine());
您需要从 while 循环中删除该分号。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.