Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Showing wrong output while reading from file in java

Tags:

java

Running this program shows the wrong output. My file "values.txt" contains 45678 and the output
after running the program is 00000.

import java.util.Scanner;
public class array{
    public static void main(String[] args)throws IOException
    {
        final int SIZE = 6;
        int[] numbers = new int[SIZE];
        int index = 0;
        File fl = new File("values.txt");
        Scanner ab = new Scanner(fl);
        while(ab.hasNext() && index < numbers.length)
        {
            numbers[index] = ab.nextInt();
            index++;
            System.out.println(numbers[index]);
        }
        ab.close();
    }
}
like image 481
6abhishek jha Avatar asked Nov 26 '14 08:11

6abhishek jha


People also ask

How do I save output in Java?

Instantiate a PrintStream class by passing the above created File object as a parameter. Invoke the out() method of the System class, pass the PrintStream object to it. Finally, print data using the println() method, and it will be redirected to the file represented by the File object created in the first step.

How read data from line from file in Java?

Java Read File line by line using BufferedReader We can use java. io. BufferedReader readLine() method to read file line by line to String. This method returns null when end of file is reached.

What is the best way to read a file in Java?

You can use BufferedReader to read large files line by line. If you want to read a file that has its content separated by a delimiter, use the Scanner class. Also you can use Java NIO Files class to read both small and large files.

How do you read and write in the same text file in Java?

You can't open the same file to read and write at the same time. You have to open and save the file information in a data structure and then close it. Then you have to work with the data structure in memory and open the file to write results. And when you finish to write you should close it.


2 Answers

You first assign to numbers[index] then increase index and output numbers[index] (for the next empty value).

Swap index++ and System.out calls.

like image 101
StanislavL Avatar answered Sep 16 '22 12:09

StanislavL


Move index++ to after the System.out.println call.

At the moment you're always outputting an unassigned value of numbers. (In Java every element in an array of int is initialised to zero).

An alternative would be to discard index++; entirely and write System.out.println(numbers[index++]);. I personally find that clearer.

like image 40
Bathsheba Avatar answered Sep 16 '22 12:09

Bathsheba