简体   繁体   中英

the line number while reading file needs to be skipped accordingly(read more)

i wish to read multiple files with multiple lines and read the files one by one. and from every file i want every 3rd line to be stored in an string array( ie line number 1,4,7,10,.... and so on must be stored in the string array) i tried this code but it still saves every line of all three files in the array. but i want to skip two lines and add every third line in the array. help me out here.

here is the code

import java.io.*;
import java.util.*;

public class music {
public double xx[] = new double[5];
public String songs[] = new String[40000];
//public static File f = new File("C:/Users/Prashant/Desktop/OCEAN/f.txt");
public static File[] fileList1 = new File("C:/Users/Prashant/Desktop/MUSIC/Categories").listFiles();

public void selectsongs() throws IOException, FileNotFoundException, ArrayIndexOutOfBoundsException //, NoSuchElementException
{
    int i;
    int lineno = 1;
    int songno = 0;
    String t = "";
    xx[0]=51;
    xx[1]=10;
    xx[2]=60;
    xx[3]=60;
    xx[4]=60;

    if (xx[0] >= 50 && xx[1] < 50 && xx[2] >= 50 && xx[3] >= 50 && xx[4] >= 50) {
        for (i = 0; i < 3; i++) {
            Scanner scanner1 = new Scanner(fileList1[i]);
            lineno = 1;
            while (scanner1.hasNextLine()) {
                t = "";
                if (lineno % 3 == 1) {
                    t = t + scanner1.nextLine();
                    songs[songno] = t;
                    songno++;
                }
                lineno++;
            }
        }
    }
    for(int j=0;j<songno;j++)
    {
        System.out.println(songs[j]);
    }
}
public static void main(String args[])
{

}
}

The Scanner will only advance by a line if you call nextLine . hasNextLine does not affect the state. So you must call nextLine in every iteration of the while loop but only place the return value in the array when appropriate.

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