user3460845
user3460845

Reputation: 29

How to read last line with Scanner.nextLine()?

I'm working on homework and i have to read input with nextLine() method. When i copied all input lines and pasted on console, the program don't read final line. How can i solve this problem.

What i need :

line1
line2
line3

What i get:

line1
line2

Here is my code

public class Name{
    public static void main(String [] args){
        Scanner scn = new Scanner(System.in);
        str = scn.nextLine();

        while(scn.hasNextLine()){
        .
        .
        .
        str = scn.nextLine();
        }
        scn.close();
    }
}

Upvotes: 2

Views: 3687

Answers (2)

Peter Lawrey
Peter Lawrey

Reputation: 533870

How about

public void main(String [] args){
    Scanner scn = new Scanner(System.in);
    while (scn.hasNextLine()) {
        String str = scn.nextLine();
        System.out.println(str);
    }
    // don't close System.in as we didn't create it.
}

When I run

$ cat > text
line1
line2
line3
^D
$ java -cp . Example < text
line1
line2
line3

Upvotes: 3

Makoto
Makoto

Reputation: 106508

I don't see any reason to check for null - you should be using scn.hasNextLine() instead, which will stop iteration when there are no more lines in the file for the Scanner to read.

Here's a code sample - we move the reading of System.in into the loop, and add a stopping condition so you don't get an infinite loop.

Scanner scn = new Scanner(System.in);
String str;

while(scn.hasNextLine()){
    str = scn.nextLine();
    System.out.println(str);
    if(str.equalsIgnoreCase("stop")) {
        break;
    }
}

Upvotes: 4

Related Questions