0

I want to know what's happening here.

With this code works perfectly

import java.util.*;

public class PruebaPersona {

public static void main(String[] args) {
    // TODO Auto-generated method stub


    Scanner entrada= new Scanner(System.in);


    String nombre, dni;
    int edad;
    char sexo;
    double peso, altura;



    System.out.println("¿Cuál es tu nombre?");
    nombre = entrada.nextLine();

    System.out.println("¿Cuál es tu DNI?");
    dni= entrada.nextLine();

    System.out.println("¿Cuántos años tienes?");
    edad = entrada.nextInt();

    System.out.println("¿Cuál es tu sexo?(Introduce H/M)");
    sexo=entrada.next().charAt(0);

But if I change the order of the inputs, like this package EjerciciosPropuestos;

import java.util.*;

public class PruebaPersona {
public static void main(String[] args) {
    // TODO Auto-generated method stub


    Scanner entrada= new Scanner(System.in);


    String nombre, dni;
    int edad;
    char sexo;
    double peso, altura;



    System.out.println("¿Cuál es tu nombre?");
    nombre = entrada.nextLine();


    System.out.println("¿Cuántos años tienes?");
    edad = entrada.nextInt();

    System.out.println("¿Cuál es tu DNI?");
    dni= entrada.nextLine();

    System.out.println("¿Cuál es tu sexo?(Introduce H/M)");
    sexo=entrada.next().charAt(0);

The program jump automatically. The output is ¿Cuál es tu DNI? and whitout wait an input ¿Cuál es tu sexo?(Introduce H/M)

Miguel27
  • 101
  • 3
  • I think your problem has to do with when you move it around you are putting `nextInt()` before `nextLine()`, thus the linked duplicate, but you didn't make it completely clear which order the entire program is when you change the order. – Nexevis Jan 16 '20 at 19:48
  • Scanner is skipping nextLine() when down there is next() but doesn't happen when there is nextInt() up of next() – Miguel27 Jan 16 '20 at 19:53
  • It has to do if `next` either `nextInt` is _before_ a `nextLine` due to not consuming the line terminator, not after. After seeing your edit, I can confirm what I said originally is what is happening. Your `nextInt` is used before `nextLine` causing the issue, you are getting confused on where the problem is. Please read the link I gave, it answers your question. – Nexevis Jan 16 '20 at 19:56
  • I've already edit it with the code order – Miguel27 Jan 16 '20 at 19:58
  • Yes I already read your edit, the link I gave is what is happening in your code. I told you what the issue is two times...All you would need to do to fix it is put an _extra_ `entrada.nextLine()` after `entrada.nextInt()`. – Nexevis Jan 16 '20 at 19:59
  • Thank you very much Nexevis! – Miguel27 Jan 16 '20 at 20:00

0 Answers0