Hi, I'm having a problem when I implement a Scanner in a Switch structure. Here's an example of how I have my code.
Problem:
When I run the program I skip the case of the switch, it does not allow me to enter the data and the program continues. My problem, unlike others, is that the program does not stop being able to enter the data, it executes the case and it goes on when it reaches scanner.nextLine();
I tried:
I'm doing it with a case structure (switch), by modifying my code and by putting this line micurso.setNombre("Programacion");
Instead of micurso.setNombre(scanner.nextLine());
It works perfectly but my intention is for the user to enter the name by keyboard.
My code so far:
import java.util.Scanner;
public class Ejercicio {
public static void main(String[] args) {
String passwd, user,passwd2,user2;
boolean correcto=false;
int opcion;
Scanner scanner=new Scanner(System.in);
Cursos micurso=new Cursos();
user="acoidan";
passwd="root";
do {
System.out.println("Introduce tu usuario y contraseña");
System.out.print("Usuario: ");
user2=scanner.nextLine();
System.out.print("Contraseña: ");
passwd2=scanner.nextLine();
if (user.equals(user2) && passwd.equals(passwd2)){
System.out.println("Bienvenido al programa");
correcto=true;
do {
System.out.println("-----------------------");
System.out.println("Curso:");
System.out.println("1. Añadir curso.");
System.out.println("2. Listar curso.");
System.out.println("-----------------------");
System.out.println("Alumnos:");
System.out.println("3.Añadir alumno.");
System.out.println("4. Listar alumnos.");
System.out.println("-----------------------");
System.out.println("0. Salir");
opcion=scanner.nextInt();
switch (opcion){
case 1:
System.out.println("Nombre del curso: ");
micurso.setNombre(scanner.nextLine());
break;
case 2:
System.out.println("Opcion 2");
System.out.println(micurso.consultaNombre());
break;
case 3:
System.out.println("Opcion 3");
break;
case 4:
System.out.println("Opcion 4");
break;
default:
opcion=0;
break;
}
}while (opcion!=0);
}else {
System.out.println("Usuario o contraseña incorrecta");
}
}while (correcto==false);
}
}
And the other class I have:
class Cursos {
String nombre;
String consultaNombre(){
return nombre;
}
void setNombre(String nombre){
this.nombre=nombre;
}
}
Thanks in advance to anyone who wants to help.