简体   繁体   中英

BufferedReader awaits for an user promt to read next line

I'm currently trying to solve Prime Generator problem from sphere online judge ( http://www.spoj.pl/problems/PRIME1/ ).

The core problem its already been solved, the issue I'm faced with is when reading the input, it reads well the first 2 lines and to read the 3rd line i have to press enter, this little thing is giving me a timeout on the evaluation of the solution. i would like to know if there is someway around so it reads the whole input without needing me to press enter.

here's the input and output

Input:

2
1 10
3 5

Output:

2
3
5
7

3
5

and here's my code

class Solucion_Prime_Generator {

    public static void main(String[] args) throws NumberFormatException,
            IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        int t = Integer.parseInt(reader.readLine());
        for(int i=0;i<t;i++) 
        {
            String numbers = reader.readLine();             
            System.out.println(numbers);
            String[] numberArray = numbers.split(" ");
            for (int j = Integer.parseInt(numberArray[0]); j <= Integer.parseInt(numberArray[1]); j++)
            {
                if(isPrime(j)){

                    System.out.println(j);
                }
            }
            System.out.println(" ");
        }
    }

    public static boolean isPrime(int n)
    {

        if( n==1)
        {
            System.out.println();
            return false;
        }
        if(n==2)
        {
            return true;
        }
        if(n%2==0){
            return false;
        }
            for (int i = 3; i*i <= n; i+=2) 
            {

            if(n%i==0)
            {               
                return false;
            }

        }

        return true;
    }

}

It's not a line until you press enter. How does it know you are done typing the line?

It's a bit hard to tell exactly what you're trying to accomplish but the readLine() method must be terminated by a carriage return or linefeed or both.

See this:

http://docs.oracle.com/javase/1.3/docs/api/java/io/BufferedReader.html#readLine ()

I believe that the problem occurs in the last line in your file, doesn't it? In this case, the last line was the third one. Probably, it was the last line in your file, without no carriage return/linefeed.

As tjg84 pointed out, readLine() expects lines to end with carriage return or linefeed or both. Hence, you have two possible solutions: - insert a carriage return / linefeed at the end of the last line. - use another method to read the line. Maybe you could use the Scanner class method nextLine() ;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM