Excepción en Thread Main Java.Util.NoSuchElementException: No se encontró ninguna línea
Este tutorial demuestra cómo resolver la Excepción en el subproceso "principal" java.util.NoSuchElementException: No se encontró ninguna línea
en Java.
Excepción en el subproceso "principal" java.util.NoSuchElementException: no se encontró ninguna línea
La excepción java.util.NoSuchElementException
es una excepción no verificada en tiempo de ejecución. La JVM genera esta excepción cuando usamos métodos como next()
, nextElement()
, iteradores o métodos o enumeraciones.
El error Excepción en el hilo "principal" java.util.NoSuchElementException: No se encontró ninguna línea
ocurre cuando estamos usando un Escáner
para obtener la entrada del usuario con métodos como nextLine()
; el error ocurrirá cuando intentemos usar el método sin ningún límite.
Probemos un ejemplo que demuestra este error.
package delftstack;
import java.util.Scanner;
public class Example {
static boolean[][] Articles;
public static void main(String[] args) {
// This initiates all array values to be false
Articles = new boolean[4][4];
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
Articles[i][j] = false;
}
// Welcome message
System.out.println("-------------------------");
System.out.println("Welcome to Delftstack.com.");
System.out.println("-------------------------\n");
// Starts program
Programstart();
}
}
public static void Programstart() {
// to read users' input
Scanner sc = new Scanner(System.in);
// user input
String Requested_Lanuguage;
String Requested_Article;
// Counters for articles array
int Count_Language = 0;
int Count_Artciles = 0;
// User to select their choice of Programming Language
System.out.print("Please type 1 for Java or 2 for Python: ");
// Language preference
Requested_Lanuguage = sc.nextLine();
switch (Requested_Lanuguage) {
case "1":
// User selects Java
System.out.println(">>> You have selected Java. \n");
break;
case "2":
// User selects Python
System.out.println(">>> You have selected Python. \n");
break;
default:
// User has not selected a valid Programming Language
System.out.println(">>> You have not selected a valid choice. Please try again. \n");
Programstart();
break;
}
// user to select their choice of article
System.out.print("Please type 1 for Web and 2 for App: ");
// Article preference
Requested_Article = sc.nextLine();
switch (Requested_Article) {
case "1":
// User selects Web Articles
System.out.println(">>> You have selected Web Articles. \n");
break;
case "2":
// User selects App Articles
System.out.println(">>> You have selected App Articles. \n");
break;
default:
// User has not selected a valid article
System.out.println(">>> You have not selected a choice. Please try again. \n");
Programstart();
break;
}
// Closes Scanner
sc.close();
}
}
La salida para el código anterior es:
-------------------------
Welcome to Delftstack.com.
-------------------------
Please type 1 for Java or 2 for Python: 1
>>> You have selected Java.
Please type 1 for Web and 2 for App: 1
>>> You have selected Web Articles.
Exception in thread "main" -------------------------
Welcome to Delftstack.com.
-------------------------
Please type 1 for Java or 2 for Python: java.util.NoSuchElementException: No line found
at java.base/java.util.Scanner.nextLine(Scanner.java:1651)
at delftstack.Example.Programstart(Example.java:45)
at delftstack.Example.main(Example.java:24)
El error ocurre porque usamos el método nextLine()
sin ningún límite. Para solucionar este problema necesitamos reemplazar el código Requested_Article = sc.nextLine();
al siguiente código.
while (sc.hasNextLine()) {
Requested_Article = sc.nextLine();
// Switch condition here
}
Probemos la solución.
package delftstack;
import java.util.Scanner;
public class Example {
static boolean[][] Articles;
public static void main(String[] args) {
// This initiates all array values to be false
Articles = new boolean[4][4];
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
Articles[i][j] = false;
}
// Welcome message
System.out.println("-------------------------");
System.out.println("Welcome to Delftstack.com.");
System.out.println("-------------------------\n");
// Starts program
Programstart();
}
}
public static void Programstart() {
// to read users' input
Scanner sc = new Scanner(System.in);
// user input
String Requested_Lanuguage;
String Requested_Article;
// Counters for articles array
int Count_Language = 0;
int Count_Artciles = 0;
// User to select their choice of Programming Language
System.out.print("Please type 1 for Java or 2 for Python: ");
// Language preference
Requested_Lanuguage = sc.nextLine();
switch (Requested_Lanuguage) {
case "1":
// User selects Java
System.out.println(">>> You have selected Java. \n");
break;
case "2":
// User selects Python
System.out.println(">>> You have selected Python. \n");
break;
default:
// User has not selected a valid Programming Language
System.out.println(">>> You have not selected a valid choice. Please try again. \n");
Programstart();
break;
}
// user to select their choice of article
System.out.print("Please type 1 for Web and 2 for App: ");
// Article preference
while (sc.hasNextLine()) {
Requested_Article = sc.nextLine();
switch (Requested_Article) {
case "1":
// User selects Web Articles
System.out.println(">>> You have selected Web Articles. \n");
break;
case "2":
// User selects App Articles
System.out.println(">>> You have selected App Articles. \n");
break;
default:
// User has not selected a valid article
System.out.println(">>> You have not selected a choice. Please try again. \n");
Programstart();
break;
}
}
// Closes Scanner
sc.close();
}
}
El código anterior no arrojará la Excepción en el hilo "principal" java.util.NoSuchElementException: No se encontró línea
ahora. Ver la salida:
-------------------------
Welcome to Delftstack.com.
-------------------------
Please type 1 for Java or 2 for Python: 1
>>> You have selected Java.
Please type 1 for Web and 2 for App: 1
>>> You have selected Web Articles.
1
>>> You have selected Web Articles.
>>> You have not selected a choice. Please try again.
Please type 1 for Java or 2 for Python:
Sheeraz is a Doctorate fellow in Computer Science at Northwestern Polytechnical University, Xian, China. He has 7 years of Software Development experience in AI, Web, Database, and Desktop technologies. He writes tutorials in Java, PHP, Python, GoLang, R, etc., to help beginners learn the field of Computer Science.
LinkedIn FacebookArtículo relacionado - Java Exception
- Arreglar Java.Net.SocketException: error de tubería rota en Java
- Clase de excepción Java Throwable VS
- Comprender la excepción de tiempo de ejecución en Java
- Corrija la excepción Java.Net.BindException: la dirección ya está en uso: Bind
- El proceso de Java Gateway se cerró antes de enviar su número de puerto
- Excepción de entrada no válida en Java