java - 为什么我的数组由不打印到控制台的方法返回?
问题描述
我正在编写一个程序,该程序将一个 .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 循环中删除该分号。
推荐阅读
- spring - Spring Boot 应用程序中的多个 RedisConnectionFactories
- c# - 指定的包含路径无效。EntityType 未使用继承集合中的名称声明导航属性
- node.js - 如何在没有错误的情况下为 node.js 安装 strongloop?
- javascript - 在javascript中复制到剪贴板不起作用
- c# - 在 C# MVC 中使用剑道 UI 网格层次结构的客户端模板时,剑道主自动增量 ID 显示在子网格中
- java - 初始化上下文:属性占位符取决于 Maven 配置文件
- r - 从 Leaflet Map R 中删除国家名称等
- sql - SQL Join 和 Distinct 和 Max 问题
- javascript - How to handle an array of Promises then/catch
- bluetooth-lowenergy - 修改蓝牙低功耗扫描参数