简体   繁体   中英

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));
}

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();
    }

您总是替换data1的内容,在while循环中使用:

data1 += scanner.nextLine();

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

}

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.

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.

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