Problem when implementing a Scanner in a Switch structure

0

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.

    
asked by Acoidan Negrín Socorro 19.12.2017 в 02:16
source

1 answer

0

Your problem is common when using Scanner with String e Int . I have responded to this problem many times, a quick search through the website would have helped you. The solution to your problem I have explained in detail in this link, I recommend you enter the following link and read my answer carefully: doubts with java program structure . I'm sure it's going to serve you!

To solve your problem quickly, I start by telling you a few things about your code, problems and suggestions.

1. Solution to your problem with Scanner when using String and Int:

The problem is with .nextInt() . When you enter a number and press "Enter", .nextInt() only consumes the number and not the end of the line. The end of every line is \n . Therefore, when you execute .nextLine() after a .nextInt() you consume the "end of the line" and not what the user has entered by keyboard.

To solve this you must add a .nextLine() extra, between .nextInt() and .nextLine() . The .nextLine() extra will consume the "end of the line" always.

Example:

int number = scanner.nextInt();
scanner.nextLine(); // Consume "\n"
String string1 = scanner.nextLine();

Your code fixed:

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: ");
                            scanner.nextLine(); // Consume "\n"
                            micurso.setNombre(scanner.nextLine());

                            break;

                        case 2:

                            System.out.println("Opcion 2");
                            System.out.println(micurso.getNombre());
                            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);

        // Cerrar Scanner
        scanner.close();
    }
}

2. You must close the Scanner

Another problem is that you do not close the Scanner at the end of your code, when you use Scanner , you should always do scanner.close() . This is indicated by the official documentation, although many people do not, but if the bosses say it, why not do it? XDDD. You can read more about this in the official documentation in this link .

Note: I have already closed the Scanner in the previous code, you can go to the end of the code and see that I have commented on the line. :)

3. Why do you use queryName () instead of a Getter?

The Getters, in case you did not know, are used to obtain (retrieve or access) the value already assigned to an attribute. If you want to get the name of your course, you should only do micurso.getNombre() .

How to create the Getter in your class Courses:

// Getter
public String getNombre() {
        return nombre;
}

4. In your class Courses you must have an empty Constructor

An empty Constructor avoids the error "The constructor Courses () is undefined" when this class is instantiated in some other class.

How to create the empty Constructor:

// Constructor vacío
public Cursos() {
        super();
    }

5. In your class Courses you need Access Modifiers

To control the access to our attributes and methods, we use access modifiers that are nothing more than reserved words of the language that will be in charge of controlling where the members of a class will be accessible, these modifiers are: private , protected , public

These access modifiers are placed just ahead of the type of an attribute.

Example with your code in your class Courses:

// Declaración de variables
    private String nombre;

Defining the attributes private , nobody can modify them without our consent, the constructor is public to allow instances of the class from outside the file Cursos.java , and the get methods will also be public , to allow anyone to consult the value of our attributes.

With the access modifiers , we prevent our programs from having an unwanted use, such as modifying attributes by entering invalid values or calling methods that may have undesired effects.

As a general rule (good practice), it is advisable to declare all attributes as private , and when we need to check its value or modify it, use the get and methods > set .

Your class Courses arranged:

public class Cursos {

    // Declaración de variables
    private String nombre;

    // Constructor
    public Cursos(String nombre) {
        this.nombre = nombre;
    }

    /*
     * Constructor vacío
     * Evita el error "The constructor Cursos() is undefined"
     * cuando se instancia esta clase en alguna otra clase
     */
    public Cursos() {
        super();
    }

    // Getters
    public String getNombre() {
        return nombre;
    }

    // Setters
    public void setNombre(String nombre) {
        this.nombre = nombre;
    }
}

So far it's all, I hope I have helped you and cleared all your doubts and that from now on you have more experience so that you can also help other colleagues on the website. Greetings friend!.

    
answered by 19.12.2017 / 03:38
source