Actually, the code itself. First you need to count the number of lines in the code, then put them into the array:
package com.company; import java.util.Scanner; import java.io.File; public class Main { public static void main(String[] args) throws Exception { File file = new File("фильмы.txt"); Scanner scanFile = new Scanner(file); int count = 0; while (scanFile.hasNextLine()) { scanFile.nextLine(); count++; System.out.println(count); } String slova[] = new String[count]; for (int i = 0;i < slova.length;i++){ slova[i] = scanFile.nextLine(); System.out.println(slova[i]); } } } At startup, it displays the following:
1 Exception in thread "main" java.util.NoSuchElementException: No line found 2 3 at java.util.Scanner.nextLine(Scanner.java:1540) 4 5 at com.company.Main.main(Main.java:21) 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 Process finished with exit code 1 I rewrote the code using 2 scanners:
import java.util.Scanner; import java.io.File; public class Main { public static void main(String[] args) throws Exception { File file = new File("фильмы.txt"); Scanner scanFile = new Scanner(file); int count = 0; while (scanFile.hasNextLine()) { scanFile.nextLine(); count++; System.out.println(count); } scanFile.close(); String slova[] = new String[count]; Scanner scanFile2 = new Scanner(file); for (int i = 0;i < slova.length;i++){ slova[i] = scanFile2.nextLine(); System.out.println(slova[i]); } scanFile2.close(); } } And now everything works as it should:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 the shawshank redemption the godfather the dark knight schindler's list pulp fiction the lord of the rings the good the bad and the ugly fight club the lord of the rings forrest gump star wars inception the lord of the rings the matrix samurai star wars city of god the silence of the lambs batman begins die hard chinatown room dunkirk fargo no country for old men Process finished with exit code 0 Actually, I wonder what the problem is in the first version of the code? Why didn’t it work using one scanner for two cycles?
Scannercannot be restarted, so if you want to read a file twice, you will have to create two scanners. As for "no lists can be used" - well, but using only arrays you can do without two readings: just write a mini-implementation ofArrayList. That is, create an array on X (selected constant) elements. If the array is full at the next reading of the string, create a larger array (for example, twice), copy the values from the old one into it and continue the loop. Here is what is needed by those who check the task ... - Regent