Read input data to EOF in the Online Judger URI

4

Hello, I'm trying to solve the following problem below:

However,I'mhavingtroubleputtingthisEOFconditionintojava.HereinthestackIfoundsolutionsattempts,howevertheyarerelatedtotheuseoffiles,andformyproblemthereisnousefile.

Forexample:

while(fileReader.nextLine()!=null){Stringline=fileReader.nextLine();System.out.println(line);}

Butthisiswiththeuseoffile,whichisnotmycase.

MyproblemistorepresentthisEOFinjava.Here'sthepartofmycodethatI'mhavingtroublewith:

publicclassMain{publicstaticvoidmain(String[]args){while(?){//CondiçãodeparadaEOF...código...}

IfIremembercorrectly,inCIcoulddosomethinglike...

while(number!=EOF);

ButhowcanIdothisinjava?

IsolvedtheprobleminC,looklikethis:

intmain(){intN=0;while(scanf("%d",&N) != EOF){
... código ...
}

But I would like to solve in java, so far I am without solution, any tips?

    
asked by anonymous 11.04.2016 / 20:59

2 answers

3

Simple, use a BufferedReader object and call the < a href="https://docs.oracle.com/javase/8/docs/api/java/io/BufferedReader.html#readLine--"> readLine () until it returns null . Remembering that the readLine() method of class BufferedReader() returns String . And since in your exercise you are dealing with a number, simply convert String to int . Example:

import java.io.*;

public class Main {

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String linha;

        while ((linha = br.readLine()) != null) {
            int n = Integer.parseInt(linha);
            // TODO: lógica
        }
    }

}

Running some sample values in Ideone .

I had already solved this exercise in the URI a few years ago (I am the 7th placed there), and I did it using exactly the same reading code I posted above (except the logic of the problem itself, obviously).

    
11.04.2016 / 22:51
1

You can also do this as follows

 BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
 while(br.ready()){...

so when the file is finished it will exit in the while loop

    
28.07.2016 / 21:22