Hi there,
I have the following code:
import java.util.InputMismatchException;
import java.util.Scanner;
public class Input {
public static String readString() {
return _readString(null, null);
}
public static String readString(String title) {
return _readString(title, null);
}
public static String readString(String title, String error) {
return _readString(title, error);
}
private static String _readString(String title, String error) {
Scanner input = new Scanner(System.in);
boolean loop = true;
String str = null;
while(loop) {
try {
if(title != null) {
System.out.print(title);
}
str = input.nextLine();
loop = false;
} catch(InputMismatchException e) {
if(error != null) {
System.out.println(error);
}
}
}
input.close();
return str;
}
}
public class Program {
public static void main(String[] args) {
String a;
a = Input.readString("VALUE: ");
System.out.println(a);
a = Input.readString("\nVALUE: ");
System.out.println(a);
}
}
And the following output:
VALOR: Hello World!
Hello World!
VALUE: Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1516)
at Input._readString(Input.java:29)
at Input.readString(Input.java:11)
at Program.main(Program.java:21)
The first value is read without any problems but the second throws that exception. Why is this happening? I "fixed" it by removing the
input.close(); line but this makes no sense to me. First because I think that I should close the Scanner after using it and second because every time I call the _readString() method, a new Scanner instance will be created, so it doesn't make sense... At least for me, but that's why I'm posting on this forum section, cause I'm new to Java.
Can someone explain me why exactly does this happen and if possible, a better solution then to remove the input.close()? It just doesn't make any sense to me create a new Scanner instance every time I call the _readString() method and leave it there without closing it...