Nikunj Banka
Nikunj Banka

Reputation: 11395

Using buffered reader does not give Runtime error but using Scanner gives on Online judge?

I was doing this question. I submitted the following code that uses a scanner to read input.

import java.io.*;
import java.math.*;
import java.util.*;
import java.lang.*;

class Main{ 

public static void main(String[] args)throws java.lang.Exception{
    Scanner cin = new Scanner(System.in);
    TreeMap<String, Integer> map = new TreeMap<String, Integer>();
    int trees = 0;
    while(true){
        String tree = cin.nextLine();
        if(tree==null){
            break;
        }
        trees++;
        if(map.containsKey(tree)){
            map.put(tree, map.get(tree)+1);
        }else{
            map.put(tree, 1);
        }
    }
    for(String key : map.keySet()){

    }

    Iterator<String> itr = map.keySet().iterator();
    while(itr.hasNext()){
        String tree = itr.next();
        System.out.print(tree + " " );
        double percent = (double)map.get(tree)/trees*100;
        System.out.format("%.4f\n", percent);
    }

}
}

But I get a runtime error. But when I submit the same code but this time I use a buffered reader, then my answer gets accepted. Is this a problem with the judge or am I missing some feature of java's input output routines.

Should I use a buffered reader or a scanner to read data more robustly?

import java.io.*;
import java.math.*;
import java.util.*;
import java.lang.*;

class Main{ 

public static void main(String[] args)throws java.lang.Exception{
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    TreeMap<String, Integer> map = new TreeMap<String, Integer>();
    int trees = 0;
    while(true){
        String tree = br.readLine();
        if(tree==null){
            break;
        }
        trees++;
        if(map.containsKey(tree)){
            map.put(tree, map.get(tree)+1);
        }else{
            map.put(tree, 1);
        }
    }
    for(String key : map.keySet()){

    }

    Iterator<String> itr = map.keySet().iterator();
    while(itr.hasNext()){
        String tree = itr.next();
        System.out.print(tree + " " );
        double percent = (double)map.get(tree)/trees*100;
        System.out.format("%.4f\n", percent);
    }

}
}

Upvotes: 0

Views: 866

Answers (1)

Read the contracts on the methods you're using. BufferedReader#readLine() returns null if it's at EOF; Scanner#nextLine() "throws NoSuchElementException - if no line was found." If you want to use Scanner, your loop conditional needs to be checking cin.hasNextLine().

Upvotes: 3

Related Questions