I’m struggling with this code piece when using Scanner class. When introducing option 1 or 2, everything goes smooth, the program executes them and shows back the initial menu to introduce by the keyboard a new option. The problem comes with the option 3, because it executes it perfectly but when when showing the initial menu with the options, the Scanner doesn’t wait for any keyboard input from the user and throws the following exception:
(Exception in thread "main" java.util.NoSuchElementException
at java.base/java.util.Scanner.throwFor(Scanner.java:962)
at java.base/java.util.Scanner.next(Scanner.java:1503)
at practicas.Main.main(Main.java:50)
I have read that closing any Scanner(System.in) object will cause the closing of all the Scanner objects created but as well that if I create multiple Scanner objects and I close one of it, won’t affect other objects. Can anyone help to understand the functioning of Scanner for reading inputs?
Thank you in advance.
public static void main(String[] args)
{
// TODO Auto-generated method stub
int opcion=-1;
Scanner scan=new Scanner(System.in);
while (opcion!=0)
{
System.out.println("Introduce la opción deseada:");
System.out.println("0: Salir");
System.out.println("1: Calcular promedio de enteros");
System.out.println("2: Idioma de animales");
System.out.println("3: escribir y leer de un fichero");
try
{
opcion=scan.nextInt();
switch (opcion)
{
case 0:
break;
case 1:
{
calcularPromedio();
break;
}
case 2:
{
hablaDeAnimales();
break;
}
case 3:
{
leerYEscribir();
break;
}
}
}
catch(Exception e)
{
System.out.println("La opción introducida no es un número entero "+e);
}
}
scan.close();
System.out.println("Gracias!");
}
private static void calcularPromedio()
{
int [] enteros= {10,20,30,40,50};
int suma=0;
double promedio=0;
for (int index=0;index<enteros.length;index++)
{
suma+=enteros[index];
}
promedio=(double)suma/enteros.length;
System.out.println("La suma es: "+suma);
System.out.println("el promedio es: "+promedio);
}
private static void hablaDeAnimales()
{
Gato gato=new Gato();
Perro perro=new Perro();
gato.hablar();
perro.hablar();
}
private static void leerYEscribir()
{
String nombreFichero="ficheroPruebas.txt";
Scanner tempScan=new Scanner(System.in);
System.out.println("Escribe el texto que quieras");
try {
FileWriter writer= new FileWriter(nombreFichero);
String texto;
texto=tempScan.nextLine();
while(texto!="")
{
writer.write(texto+"n");
texto=tempScan.nextLine();
}
System.out.println("He escrito "+nombreFichero);
writer.close();
Scanner reader=new Scanner(new File(nombreFichero));
while(reader.hasNextLine())
{
System.out.println(reader.nextLine());
}
reader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
tempScan.close();
}
}