Advanced Scanner

So you may have realized that Scanner is needed on just about every problem. That's true, but there's one more case where you need to use Scanner. This is when you have an unknown number of lines. If you noticed on the last problems, you were given a number. What happens if I didn't give you a number. Well Scanner has a solution for us.

That solution is in the form of the in.hasNext(), in.hasNextLine(), in.hasNextInt(), in.hasNextDouble(), etc. methods of Scanner.

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

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);

        while (in.hasNextLine()) { // returns false if the file is out of lines
            String line = in.nextLine(); // takes in each line
        }
    }
}

This program will assign each line of the input to the variable line. Good luck on the next problem.

results matching ""

    No results matching ""