Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I read multiple lines and end before a certain string using Scanner in Java?

I’m trying to read multiple lines from a text file before reaching a certain string, "***", which I would then like to print out. How do I do this?
Code:

public void loadRandomClass(String filename) {
    try {
        Scanner scan = new Scanner(new File(filename));
        while((scan.hasNextLine()) && !(scan.nextLine().equals("***"))) {
        
        }
        scan.close();

    } catch (FileNotFoundException e) {
        System.out.println("Something went wrong");
        e.printStackTrace();
    }
    
}

I have tried some stuff, but it keeps skipping every 2nd line, starting from the 1st and it doesn’t stop before "***".

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The problem is that scan.nextLine() reads the line and deletes it from the buffer i suppose. Try this:


while(scan.hasNextLine()) {
   String next = scan.nextLine();
   if(next.contains("***") break;
   System.out.println(next);
}

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading