Problem Scanner class in Java when entering multiple Strings as variables [duplicate]

0

I'm doing a little program for something more complex than this one, but the main problem I have is that I need to add at least two names but when I run it skips entering the first name. Better explain me in code, this is a small example of what I would like to do:

   import java.util.Scanner;

    public class Empleados {

        public static void main(String[] args) {

            Scanner e = new Scanner(System.in);


            System.out.println("Introduce un número");
            int z = e.nextInt();

            System.out.println();

            System.out.println("Introduce nombre");
            String nombre1 = e.nextLine();

            System.out.println();

            System.out.println("Introduce nombre");
            String nombre2 = e.nextLine();

            System.out.println();


            System.out.println(z + ", " + nombre1 + ", " + nombre2);


        }
    }

I do not know if it will be a bug in the code, I'm quite a novice programming. The following result appears in the console:

  

Enter a number

     

3656

     

Enter name

     

// As you can see, here he does not let me enter a name so the result   from below comes empty.
               Enter name

     

Pedro

     

3656, Pedro

Thank you very much in advance.

    
asked by Mr Pacuss 01.12.2017 в 00:49
source

6 answers

4

Your problem is that the method nextInt does not consume the line break

The nextInt method of Scanner consumes everything the numbers you find, and nothing more. That means that the line break that you press when entering your number, and that in the buffer of Scanner is saved as \n , is not consumed:

3245\n // Scanner solo consume 3245, \n se queda

When you enter the name the first time , you actually have this:

\nPedro\n

And with nextLine , Scanner consume up to the next line break, or \n . That is, your Scanner is reading up to the first \n , and there is nothing.

Solution

The classic solution is to clean Scanner by doing nextLine after each nextInt :

System.out.println("Introduce un número");
int z = e.nextInt();
e.nextLine();

That way, the first line break will be consumed and the name will not have a line break before.

    
answered by 01.12.2017 в 01:34
3

The problem is simply that nextInt() does not consume the line feed character when it reads the number. So the next time you run nextLine() , there immediately consumes the line skip character that was left in the internal buffer of Scanner when you entered the number.

The best solutions for this problem are the proposals in the accepted answer to this question in OS: Scanner is skipping nextLine () after using next (), nextInt () or other nextFoo ()? . Choose the one you prefer:

  • You add a nextLine() just after the nextInt() , just for the purpose of consuming the line break character that was left in the buffer:

    System.out.println("Introduce un número");
    int z = e.nextInt();
    e.nextLine(); // agrega esto
    
  • Or, instead of using nextInt() , you can use nextLine() and then convert to int using Integer.parseInt(s) :

    System.out.println("Introduce un número");
    int z = Integer.parseInt(e.nextLine());
    
  • Why is it not a good idea to use the other proposed solutions to change nextLine() to next() ?

    Because next() stops consuming the string when it encounters a space. So if you enter a name that includes a space, you will have the same problem again that a name will jump, but this time the second one.

    For example, if you change all nextLine to next() , and now try to enter Juan Carlos as the first name, you will see that it will not ask for the second name, because it will take Juan as the first name, and Carlos as the second.

        
    answered by 01.12.2017 в 01:24
    0

    I recommend using next() instead of nextLine() since

      
    • next () Find and return the next full token of this scanner.
    •   
    • nextLine () Move this scanner past the current line and return the entry that was skipped.
    •   

    Therefore if you use nextLine () it will take the first value ( z ) and it will jump until obtaining the third value ( nombre2 ).

    Your code only needs the method change:

    public static void main(String[] args) {
    
        Scanner e = new Scanner(System.in);
    
    
        System.out.println("Introduce un número");
        int z = e.nextInt();
    
        System.out.println();
    
        System.out.println("Introduce nombre");
        String nombre1 = e.nextLine();
    
        System.out.println();
    
        System.out.println("Introduce nombre");
        String nombre2 = e.nextLine();
    
        System.out.println();
    
    
        System.out.println(z + ", " + nombre1 + ", " + nombre2);
    
    
    }
    

    Review this good article:

    WHAT IS THE DIFFERENCE BETWEEN NEXT () AND NEXTLINE () IN JAVA?

        
    answered by 01.12.2017 в 01:11
    -1

    A brief concept about

    next () only reads up to where it finds a space (up to a space)

    nextLine () reads everything including spaces (up to an enter).

    import java.util.Scanner;
    

    public class Practical Exercise {     public static void main (String [] args) {

    Scanner sc = new Scanner(System.in);
    
    //Declaramos las variables con sus respectivos tipos de datos
    String nombre1;
    String nombre2;
    int numero;
    
    
    System.out.println("Introduce un numero");
    numero = sc.nextInt();
    
    System.out.println("Introduce un nombre");
    nombre1 = sc.next();
    
    System.out.println("Introduce otro nombre");
    nombre2 = sc.next();
    
    
    System.out.println(numero + " ," +nombre1+" ,"+nombre2);
    
    
    
    }}
    
        
    answered by 01.12.2017 в 01:05
    -2

    Greetings, what I see about the problem is that the Scanner object, once you use it for integer data, only serves for whole data, the solution is to declare another scar for String data.

     Scanner entero = new Scanner(System.in);
     Scanner cadena = new Scanner(System.in);
    
    
    System.out.println("Introduce un número");
    int z = entero.nextInt();
    
    System.out.println();
    
    System.out.println("Introduce nombre");
    String nombre1 = cadena.nextLine();
    
    System.out.println();
    
    System.out.println("Introduce nombre");
    String nombre2 = cadena.nextLine();
    
    System.out.println();
    
    
    System.out.println(z + ", " + nombre1 + ", " + nombre2);
    

    that should work with your program

        
    answered by 01.12.2017 в 01:02
    -2

    The problem is not the Scanner, the problem is the method you use to read a String , nextLine() , it goes to the next line so ignore the first name input, try with next() .

    public static void main(String[] args) {
    
        Scanner e = new Scanner(System.in);
        System.out.println("Introduce un número");
        int z = e.nextInt();
        System.out.println();
        System.out.println("Introduce nombre");
        String nombre1 = e.next();
        System.out.println();
        System.out.println("Introduce nombre");
        String nombre2 = e.next();
        System.out.println();
        System.out.println(z + ", " + nombre1 + ", " + nombre2);
    
    }
    

    next ()

      

    Returns the following token if it matches the pattern built to   from the specified chain.

    nextLine ()

      

    Move this scanner past the current line and return the entry   who jumped.

        
    answered by 01.12.2017 в 01:06