0

i want to Scan a String and a int inside a for loop with a Scanner Class. When i try to run the programm, i get this error:

 java.util.NoSuchElementException: No line found
    at java.base/java.util.Scanner.nextLine(Scanner.java:1651)
    at u13_beziehungZuVielenObjekten.Main.main(Main.java:27)

this is my code:


 public static void main(String[] args) {
     // TODO Auto-generated method stub

     Scanner scanner2 = new Scanner(System.in);
     String nameString;
     int alter;

     for (int i = 0; i < 3; i++) {

         System.out.println("Name Mitlgied?");
          nameString = scanner2.nextLine();

         System.out.println("Alter Mitglied?");
          alter = scanner2.nextInt();

         Mitglied mitglied = new Mitglied(alter, nameString);

         verein.addMitglied(mitglied, i);
 
     }
     scanner2.close();
     
 }

}

Zabuzard
  • 20,717
  • 7
  • 45
  • 67
  • After this line of your code: `alter = scanner2.nextInt();`, insert the following line: `scanner2.nextLine()` and then run your code again. – Abra Jun 26 '20 at 18:08
  • `NoSuchElementException: No line found` means that there are no more lines to be read. This may happen when Scanner reached end of data, which in case of streams means that they got closed. This suggests that in some other part of your code you are closing either `System.in` directly or indirectly (maybe by creating some other Scanne which wraps it and is being closed, which also closes `System.in`). – Pshemo Jun 26 '20 at 18:08
  • My guess is that you may created other scanners because you faced problem described at [Scanner is skipping nextLine() after using next() or nextFoo()?](https://stackoverflow.com/q/13102045). Don't do it. Create one scanner which handles `System.in` and reuse it in other places which need it along with solutions from linked question (my preferred solution is described at https://stackoverflow.com/a/39949330) – Pshemo Jun 26 '20 at 18:11

0 Answers0