简体   繁体   中英

Using scanner and a text file to get a certain string in a line

So I want scanner to analyze each line of a text file and stop after an x amount of words, in this case x=3.

My code looks something like this :

    scannerName.nextLine();
    scannerName.next();
    scannerName.next();
    scannerName.next();

Well, the problem here is that nextLine() advances the scanner past the current line AS WELL AS return a string. So if I call next(), that will just find the next string which is on the next line (right?).

Is there a way to do what I'm asking?

Thank you

Try the following code : - while(scannerName.hasNext() != null) {

scannerName.next(); //Returns the 1st word in the line
scannerName.next(); //Returns the 2nd word in the line
scannerName.next(); //Returns the 3rd word in the line
//Analyze the word.
scannerName.nextLine();

}

Your question is not so precise, but i have a solution for reading from txt-files:

Scanner scan = null;
    try {
        scan = new Scanner(new File("fileName.txt"));                       
    } catch (FileNotFoundException ex) {
        System.out.println("FileNotFoundException: " + ex.getMessage());
    } catch (Exception e) {
        System.out.println("Exception: " + e.getMessage());
    }

    int wordsRead = 0;
    int wordsToRead = 3;                               //== You can change this, to what you want...
    boolean keepReading = true;

    while (scan.hasNext() && keepReading) {
        String currentString = scan.nextLine();        //== Save the entire line in a String-object 
        for (String word : currentString.split(" ")) {
            System.out.println(word);                  //== Iterates over every single word - ACCESS TO EVERY WORD HAPPENS HERE
            wordsRead++;
            if (wordsRead == wordsToRead) {
                keepReading = false;                   //== makes sure the while-loop will stop looping
                break;                                 //== breaks when your predefined limit is is reached
            } //== if-end
        } //== for-end
    } //== while-end

Let me know if you have any questions :-)

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