Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

183
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda