DEV Community

Beatriz Maciel
Beatriz Maciel

Posted on • Edited on

3

HackerRank #6 | Scanner e End-of-file | 🇧🇷

Scanner

Um Scanner serve para ler um input. A sintaxe é:


Scanner sc = new Scanner (System.in);
    /...
    sc.close();                     

Enter fullscreen mode Exit fullscreen mode

É importante fechar o Scanner antes de fechar o main.

=============

Java End-of-file

No caso desse exercício que pede para ler linha a linha (sem delimitação prévia de quantas linhas totais), adicionando o número de cada linha antes do input (o input é uma String), achei a seguinte solução:

  • Criar um new Scanner
  • Criar um integer i que inicia em 1
  • Criar um while que passa um Scanner com o método .hasNext()
  • Imprimir o input com System.out.println(i + " " + sc.nextLine());

^ o .nextLine serve para o programa esperar uma linha para continuar a rodar. Sem o .nextLine(), o programa roda eternamente depois do primeiro input.

  • Somar +1 ao integer para voltar ao início do loop.
  • Fechar o Scanner.

O código final fica assim, dentro da main:


Scanner sc = new Scanner(System.in);
int i = 1;
while(sc.hasNext()){
     System.out.println(i + " " + sc);
     i++;
}
sc.close();

Enter fullscreen mode Exit fullscreen mode

============

Essa publicação faz parte de uma série de exercícios resolvidos em Java no HackerRank. Acesse a série completa:

Top comments (0)

Great read:

Is it Time to go Back to the Monolith?

History repeats itself. Everything old is new again and I’ve been around long enough to see ideas discarded, rediscovered and return triumphantly to overtake the fad. In recent years SQL has made a tremendous comeback from the dead. We love relational databases all over again. I think the Monolith will have its space odyssey moment again. Microservices and serverless are trends pushed by the cloud vendors, designed to sell us more cloud computing resources.

Microservices make very little sense financially for most use cases. Yes, they can ramp down. But when they scale up, they pay the costs in dividends. The increased observability costs alone line the pockets of the “big cloud” vendors.