(Fixed) fix in java when entering 2 words in the same array address

0

In class we are seeing arrangements in java and they ask me for a program that:

  • Ask how many names you want to enter.

  • Print them.

  • something like this:

    [0] = "Alejandro Sanchez";
    [1] = "Fernando Ortega";
    

    The only thing I could do is enter a word to the arrangement. like this:

    [0] = "Alejandro"
    [1] = "Sanchez"
    

    Fixed, add a second Scanner, one to store the size of the array and the other to store the array data

    package ejer24tap_vectornombres;
    import java.util.*;
    /**
    *
    * @author Carlos Vazquez Lara, 4S11.
    */
    public class Ejer24Tap_vectornombres {
        public Ejer24Tap_vectornombres(){
            Scanner lee=new Scanner(System.in);//almacena el tamaño del array
            Scanner lee1=new Scanner(System.in);//almacena los datos del array
            int tam=0;
            System.out.println("Cuantos nombres desea ingresar: ");
            tam=lee.nextInt();
            String[] nombres = new String[tam];
            for (int i = 0; i < nombres.length; i++) {
                System.out.prinln("Ingrese el nombre #"+i);
                nombres[i]=lee1.next();
            }
            for (int j = 0; j < nombres.length; j++) {
                System.out.println("Nombre ["+j+"] "+nombres[j]);
            }
        }
    
        public static void main(String[] args) {
            new Ejer24Tap_vectornombres();
    
        }
    
    }
    
        
    asked by Carlos7 05.10.2018 в 05:51
    source

    2 answers

    1

    By doing lee.next() within the for you will take the first token and the spaces separate tokens that is why what you say happens to you.

    You have to use lee.nextLine() to get the whole line taken.

    In your example

    for (int i= 0; i<nombres.lenght;i++){
        System.out.println("Ingrese el nombre #"+i);
        nombres[i]=lee.nextLine();
    }
    
        
    answered by 05.10.2018 / 08:31
    source
    0

    You should not use Scanner for this type of problem. According to the documentation of the JDK, Scanner is a simple token collector that receives an InputStream nothing else, that's why the next method is returning every "word" in each position. However, the class also has a method to be able to read a complete line Scanner::nextLine . You can check the official documentation link

        
    answered by 05.10.2018 в 09:13