简体   繁体   English

Java-从文件读取返回null

[英]Java - reading from file returns null

This question has been asked a few times before on stack overflow and I wanted to stress that I have looked into the solutions and yet to overcome my problem. 在堆栈溢出之前已经问过几次这个问题,我想强调一点,我已经研究了解决方案,但仍未解决我的问题。

I have an program that should read data from a file and store it within the array. 我有一个程序应该从文件中读取数据并将其存储在数组中。 I am currently running some tests to ensure the data is being read correctly and one of these are a simple output to the terminal. 我目前正在运行一些测试,以确保正确读取数据,其中之一是向终端的简单输出。 Each time I wanted to print out the data, I keep getting "null". 每次我想打印数据时,我都会一直为“ null”。

Looking into the problem I set each of the array elements to "". 调查问题,我将每个数组元素设置为“”。 So I initialised them. 所以我初始化了它们。 Now the terminal just displays a blank line. 现在终端仅显示一个空行。 It seems the content from the file isn't being read to the array? 似乎文件中的内容没有被读取到数组中?

the file being read content: 正在读取的文件内容:

Q1: (A + B)*(A+B) \n 1. A*A + B*B \n 2. A*A +A*B + B*B \n 3. A*A +2*A*B + B*B \n
Q2: (A + B)*(A - B) \n 1. A*A + 2*B*B \n 2. A*A - B*B \n 3. A*A -2*A*B + B*B \n
Q3: sin(x)*sin(x) + cos(x)*cos(x) \n 1. 1 \n 2. 2 \n 3. 3 \n

How I am reading it(code snippet is in a method): 我如何阅读它(代码片段在一种方法中):

try 
{
    int i =0;
    String [] line = new String [10];
    for (i=0;i<=9;i++)
    {
        line[i] = "";
    }
    Scanner scanner = new Scanner(new File("questions.txt"));
    scanner.useDelimiter("Q");
    i=0;
    while (scanner.hasNext()) 
    {
        line[i] = scanner.next();
        i++;
        System.out.println("" + line[i]);
    }
}
catch (FileNotFoundException exp)
{
    exp.printStackTrace();
}

You have an i++; 你有一个i++; before the sysOut. 在sysOut之前。 I think that's why you're not seeing the contents read. 我认为这就是为什么您看不到阅读的内容。 Try switching the two statements. 尝试切换两个语句。

Here is your problem 这是你的问题

  line[i] = scanner.next();
  i++; // Incrementing the Index before printing
  System.out.println("" + line[i]);

Try this 尝试这个

  line[i] = scanner.next();
  System.out.println("" + line[i++]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM