Home » Java » java – Getting NoSuchElementException while reading a variable-Exceptionshub

java – Getting NoSuchElementException while reading a variable-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

I’am trying to call a method called “cnpPacient”.After running this i get a NoSuchElementException in the line where i read variable ” cnp “.

static void cnpPacient() {
    Scanner x = new Scanner(System.in);
    System.out.println("INTRODUCETI CNP-ul PACIENTULUI :");
    int cnp = x.nextInt();
    x.close();
}

How can i fix it ?

How to&Answers:

Works fine for me when provide 2 as input and it printed the same.

public static void main(String[] args) {
     cnpPacient();
}

static void cnpPacient() {
    Scanner x = new Scanner(System.in);
    System.out.println("INTRODUCETI CNP-ul PACIENTULUI :");
    int cnp = x.nextInt();
    System.out.println(cnp);
    x.close();
}

Output:

INTRODUCETI CNP-ul PACIENTULUI :
2
2