Purple_Rain
Purple_Rain

Reputation: 77

read Line by Line, in java feed in to an array

   1
   0
   0
   0
   1
   1
   1

Have a text file that has to be read line by line to code below in the array, however it only stop at the first line. As in it gets the first ineger "1" and doesn't get to the rest of the integers, line by line

String fileName = "input.txt";
File file = new File(fileName);
Scanner scanner = new Scanner(file);
//  String s = "";
while(scanner.hasNextLine()){
     data1 = scanner.nextLine();
}


for ( int i = 0; i < data1.length(); i++)
{
     covertDataArray[i] = Byte.parseByte(data1.substring( i, i+1));
}

Upvotes: 0

Views: 487

Answers (4)

lukasrozs
lukasrozs

Reputation: 123

you always replace the content of data1, in the while loop use:

data1 += scanner.nextLine();

Upvotes: 1

Denis Kulagin
Denis Kulagin

Reputation: 8947

That'll do:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class LineByLine {

    public static void main(String[] args) throws FileNotFoundException {
        String fileName = "input.txt";
        File file = new File(fileName);
        Scanner scanner = new Scanner(file);

        int len = 0;
        int [] covertDataArray = new int[100];
        while (scanner.hasNextLine()) {
            String data1 = scanner.nextLine();
            covertDataArray[len] = Integer.parseInt(data1.trim());
            len++;
        }

        for (int i = 0; i < len; i++) {
            System.out.println(covertDataArray[i]);
        }
    }

}

Upvotes: 1

Zavior
Zavior

Reputation: 6462

Let's walk through the code.

    while(scanner.hasNextLine()){
      data1 = scanner.nextLine();
    }

data1 will always have only the content of the latest line you have read in it.

To fix, simply append to the variable instead:

    while(scanner.hasNextLine()){
      data1 += scanner.nextLine();
    }

Upvotes: 3

Jake Chasan
Jake Chasan

Reputation: 6560

This may be due to the fact that "Data" is not an array. What it is doing is it is rewriting over the object data every time it iterates through the while loop.

I would recommend making Data and ArrayList (because it is a flexible array) and using that to store the data.

Here is a sample of what the code could be:

ArrayList<Integer> data1 = new ArrayList<>;
while(scanner.hasNextLine()){
     data1.addObject(scanner.nextLine());
}

If you use this method, it will not be necessary to parse the individual integers, which will improve the performance of your program.

Upvotes: 0

Related Questions