1

I'm trying to scan a text file and store the strings into an array while ignoring the first line. When I run the code it has a blank spot and the array is missing a string. Is there anyway to scan the file and have it skip over the int value and include all the strings?

File file = new File("input.txt");

    Scanner scan = new Scanner(file);



    int size = scan.nextInt();

    String[] blocks = new String[size];

    for (int i = 0; i < blocks.length; i++) {

        blocks[i] = scan.nextLine();

    }

    System.out.println(Arrays.toString(blocks));

[, MXTUAS, OQATGE, REWMNA, MBDFAC]

Ketuno
  • 13
  • 3

1 Answers1

0

Try reading the entire line each time, including for the initial integer value:

File file = new File("input.txt");
Scanner scan = new Scanner(file);

int size = Integer.parseInt(scan.nextLine());
String[] blocks = new String[size];

for (int i = 0; i < blocks.length; i++) {
    blocks[i] = scan.nextLine();
}

System.out.println(Arrays.toString(blocks));
Tim Biegeleisen
  • 387,723
  • 20
  • 200
  • 263
  • Sorry can you explain why only changing "scan.nextInt;" made it work? Whats the difference between that and "Integer.parseInt(scan.nextLine());" – Ketuno Mar 26 '19 at 05:13
  • I'm not an expert in the `Scanner` API, but it has to do with that `Scanner#nextInt()` might not consume the newline which appears after the number. So, that value then falls over to the next (first) call to `Scanner#nextLine`. – Tim Biegeleisen Mar 26 '19 at 05:14