Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

185
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!