Question

I'm reading from System.in, and I'm using the Scanner class. My problem is when I use redirection the last line in the file is not being read. I read the documentation for Scanner.readLine, and I'm guessing it's because it does not have a "end of line" character. Any idea what I can use instead to get this last line?

In my code input is "".

        Scanner scanner = new Scanner(System.in);
        int sizeOfList = scanner.nextInt();
        ArrayList<Integer> arrayList = new ArrayList<Integer>();
        String input = scanner.nextLine();
        System.out.println(input);
        String[] splitInput = input.split(" |\\n");
        for(int i = 0; i < splitInput.length; i++)
        {
            System.out.println(splitInput[i]);
            arrayList.add(new Integer(Integer.parseInt(splitInput[i])));
        }
Était-ce utile?

La solution

instead of scanner.nextLine(), you could use scanner.next() .... This will get a string from the scanner when it does not have an end of line character.

You can also call scanner.hasNextLine() to check if you have reached the line at the end that you are worried about!

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top