문제

I'm working on a code that reads user input, so I've made a procedure that does just that, reads and return the string. when calling it twice from another procedure, returns a NoSuchElementException error which I can't figure out why.

input reader proc:

    public static String read() {
    
72    Scanner leer = new Scanner(System.in);
73    String entry = leer.nextLine();
74    leer.close();
75    return entry;
    
    }

how I'm using it:

...
    System.out.println("input value ");
    String padre = Entrada.read();
    System.out.println("input values ");
27  String reemplazado = Entrada.read();
...

I'm getting

Exception in thread "main" java.util.NoSuchElementException: No line found
    at java.util.Scanner.nextLine(Unknown Source)
    at modulocarga.Entrada.leerEntradaUsuario(Entrada.java:73)
    at modulocarga.TablaSimbolica.addTaxonomica(TablaSimbolica.java:27)
    at modulocarga.Principal.main(Principal.java:8)

works fine the first time I call it then it crashes. what could it be?

도움이 되었습니까?

해결책

Since there is only one InputStream used its no longer possible to read from the closed input source the second time the method is called

Either refrain from closing the Scanner (or create a single class instance of Scanner to be closed at application end)

다른 팁

This is because your scanner is linked to System.in and when you're closing your scanner, it automatically closes System.in as well. What you want to do is to just close your scanner without closing System.in.

This would help: Close Scanner without closing System.in

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top