Balint9004
Balint9004

Reputation: 3

Java Scanner's nextLine() method gives no line found

I have wasted hours with this simple problem but I could not figure out why nextLine() cannot find the next line. Please help me, thank you!

I tried this code: https://www.geeksforgeeks.org/scanner-nextline-method-in-java-with-examples/ as an experiment and naturally it worked but my own will not.

Variable "test" is copied from the file.

Code portion:

ObservableList adatok;

@Override
public void initialize(URL url, ResourceBundle rb) {

    int lines = 0;
    try {
    File f = new File("C:\\Users\\EDU_BYQN_0965\\Documents\\NetBeansProjects\\JSZ_SB\\src\\jsz_sb\\fokonyvi_kivonat.txt");
    String test = "113,Vagyoni értékű jogok,3600,0,\n" +
            "1173,Vagyoni értékű jogok értékhelyesbítése,360,0,\n" +
            "1193,Vagyoni értékű jogok értékcsökkenése,0,2400,\n" +
            "5,t,5,5,";

    Scanner s = new Scanner(f);
    while (s.hasNext() && s.nextLine() != null) lines++;
    String[][] array = new String[lines][4];
    String[] temporary = new String[4];
    for (int i = 0; i < lines; i++) {
        temporary = s.nextLine().split(",");
        for (int j = 0; j < 4; j++) {
            array[i][j]=temporary[j];
            adatok = FXCollections.observableArrayList(
                    new TrialBalance(array[i][0], array[i][1], Integer.parseInt(array[i][2]), Integer.parseInt(array[i][3])));               
        }            
    }
            } catch (FileNotFoundException ex) {
        Logger.getLogger(FXML_scene2Controller.class.getName()).log(Level.SEVERE, null, ex);
    }

Array "temporary" should contain the first line of the file, leastwise at the first loop and runtime error should not appear.

Upvotes: 0

Views: 144

Answers (1)

Andy Turner
Andy Turner

Reputation: 140318

You exhaust the Scanner in this line:

while (s.hasNext() && s.nextLine() != null) lines++;

It stops because there are no more lines. (Note that the check hasNext() pairs with a call to next(), and hasNextLine() pairs with nextLine()).

So, if you try to read any more lines from the Scanner, there is nothing more to read.

You either need to create a new instance of the Scanner; or use a data structure that you don't need to know the size of a-priori, like a List (or resize your array as required; but there is little point in doing this "by hand" when ArrayList does that for you transparently).

Upvotes: 3

Related Questions