The first time you enter the for loop iterates twice

0

That said, the first time you enter the for loop, you iterate it twice. Then it's still normal but that's not how the first one tells me.

public static void main(String[] args)
{
    //a uno se le van presentando personas desconocidas exactas con "soy -----" y va respondiendo "hola ------"
    Scanner sc = new Scanner(System.in);

    int  n;
    String nombre;

    System.out.println("¿Cuántas personas desconoce?");
    n = sc.nextInt();

    String[] desconocidos = new String[n];

    for (int i = 0; i < desconocidos.length; i++)
    {
        System.out.print("Soy ");
        nombre = sc.nextLine();
        desconocidos[i] = nombre;
    }
    sc.close();
    for (int i = 0; i < desconocidos.length; i++)
    {
        System.out.println("Hola, "+desconocidos[i]);
    }

}

example of output:

¿Cuántas personas desconoce?
4
Soy Soy juan
Soy alberto
Soy carlos
Hola, 
Hola, juan
Hola, alberto
Hola, carlos

One I am not taking it well and it stays empty, I should be able to put the 4 names.

    
asked by AlejandroB 19.09.2018 в 12:56
source

1 answer

2

You need to do a sc.nextLine() just after your sc.nextInt() so that the program does not assign the intro that you do with the value to the next request.

public static void main(String[] args)
{
    //a uno se le van presentando personas desconocidas exactas con "soy -----" y va respondiendo "hola ------"
    Scanner sc = new Scanner(System.in);

    int  n;
    String nombre;

    System.out.println("¿Cuántas personas desconoce?");
    n = sc.nextInt();
    sc.nextLine(); //  **** Esta es la linea que te falta ****

    String[] desconocidos = new String[n];

    for (int i = 0; i < desconocidos.length; i++)
    {
        System.out.print("Soy ");
        nombre = sc.nextLine();
        desconocidos[i] = nombre;
    }
    sc.close();
    for (int i = 0; i < desconocidos.length; i++)
    {
        System.out.println("Hola, "+desconocidos[i]);
    }

}
    
answered by 19.09.2018 / 13:40
source