java - 我的数组一直打印空值。填写不当?

标签 java arrays null

我查看了其他提出的问题,大多数都使用了拆分,但我没有使用它,也没有根据我的情况得到适当的回答。正在练习数组,现在正在尝试拉取来自文件的字符串。这是我的主要类(class)

Scanner fileIn = null;  // Initializes fileIn to an empty object
  try
  {
     // Attempt to open the file
     FileInputStream file = new FileInputStream("questions.dat");
     fileIn = new Scanner(file);
  }
  catch (FileNotFoundException e)
  {
        // If the file could not be found, this code is executed
        // and then the program exits
     System.out.println("File not found.");
     System.exit(0);
  }

String line = "";
int i = 0;
String question[] = new String[5];

for(i=0; i < question.length; i++)
  {
     while(fileIn.hasNextLine())
     {
        line = fileIn.nextLine();
        System.out.println(line);
        question[i] = fileIn.nextLine();

     }
    System.out.println(Arrays.toString(question));
}

出于某种原因,当它打印 Question[] 时,它会打印 [7, null, null, null, null]。我不知道为什么。我的数组实际上没有填充字符串吗? 示例字符串。 一周有多少天?七。大多数人有多少根手指?十。这是最后一个字符串。 程序从哪里获取 null?

最佳答案

您有嵌套循环,并且仅填充数组中的第一个元素:

for(i=0; i < question.length; i++)
  {
     while(fileIn.hasNextLine())
     {
        line = fileIn.nextLine();
        System.out.println(line);
        question[i] = fileIn.nextLine();

     }
    System.out.println(Arrays.toString(question));
}

您需要删除内部循环:

for(i=0; i < question.length; i++)
  {
     if(fileIn.hasNextLine())
     {
        line = fileIn.nextLine();
        System.out.println(line);
        question[i] = line;

     }
    System.out.println(Arrays.toString(question));
}

关于java - 我的数组一直打印空值。填写不当?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33989731/

相关文章:

java - 如何得到需要的结果,结果是数组列表?

java - iText 5.0.0 RTF 和 HTML 去哪儿了?

mysql - SQL : Replacing NULL with 0 in monthly count table

c - 为什么我的代码中的 realloc() 和 free() 会失败?

java - 在 JPanel 中显示多个 JTextField 和 JLabels 时遇到困难

java - 安装 Android Studio 进行 Android 开发

java - 数组只检测输入单词的一部分而不是整个单词

java - 只打印那些是 Java 数组中另一个数字的两倍的数字

c - 使用指针知道数组的大小

ruby - 在 Ruby 中用 Nil 替换数组中的空单元格?