0

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".

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();
}
2
  • 2
    You have an i++; before the sysOut. I think that's why you're not seeing the contents read. Try switching the two statements Commented Feb 22, 2015 at 12:14
  • @VineetRamachandran Thanks. Stupid mistake I missed. Would you mind making your comment a answer so I can give the green tick? Commented Feb 22, 2015 at 12:16

2 Answers 2

1

You have an i++; before the sysOut. I think that's why you're not seeing the contents read. Try switching the two statements.

Sign up to request clarification or add additional context in comments.

Comments

0

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++]);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.