I have a problem that I can't find. I have the start class and the person class. in the start class I instantiate 5 people and in the person class I have 3 attributes which are: name, surname, language. I have created a method called request data() that requests through a scanner to enter data. I have created File and the filewriter and if I only call the method once in the start "persona.pedirDatos()" everything goes correctly, I have the problem when I put the method twice as I have it here
the start class
Persona persona1 = new Persona();
Persona persona2 = new Persona();
Persona persona3 = new Persona();
Persona persona4 = new Persona();
Persona persona5 = new Persona();
persona1.pedirDatos();
persona2.pedirDatos();
and in the Person class
protected String nombre;
protected String apellido;
protected String idioma;
//metodos propios
public void pedirDatos() throws IOException {
try (Scanner scanner = new Scanner(System.in)) {
File file = new File("datos.txt");
FileWriter writer = new FileWriter("datos.txt");
System.out.println("Nombre: ");
nombre = scanner.nextLine();
System.out.println("Apellido");
apellido = scanner.nextLine();
System.out.println("idioma");
idioma = scanner.nextLine();
file.createNewFile();
writer.write(nombre + "-");
writer.write(apellido + "-");
writer.write(idioma + "-");
writer.close();
this is the error message
Exception in thread "main" java.util.NoSuchElementException
at java.base/java.util.Scanner.throwFor(Scanner.java:937)
at java.base/java.util.Scanner.next(Scanner.java:1478)
at ACT2.Persona.pedirDatos(Persona.java:23)
at ACT2.Start.main(Start.java:19)
The problem is that both would
Scanner
use the sameInputStream
console, being a resource that cannot be shared between multiple instances, so when you close the first Scanner you closeInputStream
it and the second Scanner will not have it available, that's why the errorjava.util.NoSuchElementException
, according to the documentation, you just have to have a single instance ofScanner
throughout the life of the application. So the solution would be to instantiate the scanner in the classStart
and pass the scanner instance as a parameter in the constructor or never close the resource, I show you an example:To prevent it from
FileWriter
cleaning the file on each write, you must enable the append property to true,FileWriter("datos.txt", true)
this will make it add text to the one that is already there when you write text, another change is that the classFileWriter
is already in charge of creating the file if it does not exist, then the classFile
is redundant.