猿问

获取 null 作为数组的输出

import java.util.*;


public class a{

   public static void main(String[] args) throws FileNotFoundException {



    Scanner sc = new Scanner(new File ("master file.txt"));


    String[] ids = new String[100];



    System.out.println(ids);

while(sc.hasNext()) {

    int i = 0;

    ids[i] = sc.next();

    i++;

}

我试图将数据从文件放入数组。我总是得到一个空值作为输出。我想不通为什么。这一直非常令人紧张。


幕布斯7119047
浏览 175回答 2
2回答

慕森王

在用元素填充数组之前,您正在打印数组。您的计数器在循环的每次迭代中都i重置为。虽然使用具有固定数量元素的数组来读取未知长度的文本不是一个好主意,但还是使用一些动态数组,例如.0whileArrayList确保您提供了正确的.txt文件路径。所以你的代码可能是这样的:&nbsp; &nbsp;Scanner sc = new Scanner(new File ("C:/correct/path/to/file/master_file.txt"));&nbsp;&nbsp; &nbsp; List<String> listOfStrings = new ArrayList<String>();&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; while(sc.hasNextLine()) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;listOfStrings.add(sc.nextLine());&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; System.out.println(listOfStrings);

噜噜哒

输出为空,因为在尝试打印数组之前您从未分配过任何数组。我还将 i 移到循环之外,因此每次都不会重新初始化。此外,由于 ids 是一个数组,您需要使用 Arrays.toString(ids) 来打印它,或者您只需获取对象 id。public static void main(String[] args) throws FileNotFoundException {&nbsp; &nbsp; String[] ids = new String[100];&nbsp; //array to store lines&nbsp; &nbsp; int i = 0;&nbsp; // line index&nbsp; &nbsp; try (Scanner sc = new Scanner(new File ("master file.txt"))) { // try resource&nbsp; &nbsp; &nbsp; &nbsp; while(sc.hasNextLine()) { // check for next line&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ids[i] = sc.nextLine(); // store line to array index&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; i++;&nbsp; // increment index&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; System.out.println(Arrays.toString(ids));&nbsp; //print output.}
随时随地看视频慕课网APP

相关分类

Java
我要回答