Dushyant Singh
Dushyant Singh

Reputation: 11

BufferedReader / Scanner Last Line Reading Issue

While solving a problem at hacker-rank I am facing the issue that scanner/bufferedreader is unable to read the last. As the input provided by them is like

10

abcdefghijk

2

R 1 2

W 3 4

So both scanner/bufferedreader is unable to read the last line. If the input is like then the code seems to work fine.

10

abcdefghijk

2

R 1 2

W 3 4

(End of Input)

public class ScannerTest {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        Scanner input = new Scanner(System.in);
        int len = input.nextInt();
        input.nextLine();
        String inputString = input.nextLine();
        int qc = input.nextInt();
        input.nextLine();
        System.out.println();
        System.out.println(len + inputString + qc);
        for(int i=0;i<qc;i++){
            String l = input.next();
            int le = input.nextInt();
            int ri =  input.nextInt();
            input.nextLine();
            System.out.println(l+le+ri);
        }
        input.close();
    }
}

Here is the sample code which I am using. I know that we need a \r or\n at the end of line to readline from scanner / bufferedreader. But can anyone provide a solution to this issue as input comes from system that is predefined.

Upvotes: 1

Views: 231

Answers (2)

GhostCat
GhostCat

Reputation: 140613

The problem is here:

input.nextLine();
String inputString = input.nextLine();

You are consuming a line to just throw it away.

The other thing is: especially when dealing with standard libraries - don't assume that something is broken/doesn't work. In 99,999% of all case the problem is something within your code.

Upvotes: 1

Joop Eggen
Joop Eggen

Reputation: 109613

BufferedReader would read the last line even if it does not end in a line break. System.in is the culprit, that does its own line buffering. A native system thing: suppose you pressed a couple of backspaces to change the last number...

Upvotes: 3

Related Questions