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();
}
You have an i++;
before the 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++]);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.