Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

189
Visualizações
Unexpected behavior of Scanner

In below code have two methods scanner1 and scanner2 in both methods new object of Scanner is created and scanning the input after that closing the Scanner by invoking close().

import java.util.Scanner;

public class TestScanner {

    public static void scanner1(){
        Scanner sc = new Scanner(System.in);//created object of scanner
        System.out.println("Enter string :");
        String input = sc.nextLine(); //scanning input
        sc.close(); //closing scanner object
    }

    public static void scanner2(){//problem in scanner2
        Scanner sc = new Scanner(System.in);//created another scanner object
        System.out.println("Enter String :");
        String input = sc.nextLine();//scanning object
        sc.close();//closing the input
    }


    public static void main(String[] args) {
        scanner1();
        scanner2();//problem here

    }

}

For scanner1 method working fine but when scanner2 method get invoked getting the below error:

Enter string : India Exception in thread "main"

java.util.NoSuchElementException: No line found Enter String : at java.util.Scanner.nextLine(Unknown Source) at cheggapril.TestScanner.scanner2(TestScanner.java:17) at cheggapril.TestScanner.main(TestScanner.java:24)

Problem is why in scanner2 method scanner not able to scan the user input even in this method creating fresh one object of Scanner. Please give some clear explanation. any ref or example will be much greatful.

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

The reason is quite simple, closing the 1st scanner object closes internally too the input stream which is actually being used by the second scanner

your options are: use only one scanner or close those when you are sure all of them are not required anymore..

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda