1

I have a problem with my code, in a loop of an array I enter the number but the first element of array doesn't enter and skip. Please tell me what is my wrong in the code?

Scanner sc= new Scanner(System.in);
    int j;
    String correos=new String();
    int largo;
    System.out.println("------Cuantas direcciones va a ingresar?----");
    largo=sc.nextInt();
    String Correos[]=new String[largo];
    for(int i=0; i<Correos.length; i++){
       System.out.println("------Introduzca esas direcciones----");
       Correos[i]=sc.nextLine();
       
       }
    System.out.println(Arrays.toString(Correos));
    }
    
//Output
------Cuantas direcciones va a ingresar?----
3
------Introduzca esas direcciones----
------Introduzca esas direcciones----
ddddd
------Introduzca esas direcciones----
dddd
[, ddddd, dddd]

2 Answers 2

1

the problem is with sc.nextLine() it take the enter key after you typing the number and pressing the enter key, so you should change the code:

for (int i = 0; i < Correos.length; i++) {
    System.out.println("------Introduzca esas direcciones----");
    Correos[i] = sc.next();
}
Sign up to request clarification or add additional context in comments.

Comments

1

The issue here is, that sc.nextInt() does not flush the scanner buffer after pressing Enter. This means, you have a remaining Enter within the buffer. When you call sc.nextLine() for the first time, it will be automatically filled with the remaining data in the buffer.

Your code works as expected if you replace reading the number with the following line:

largo = Integer.valueOf(sc.nextLine());

The code above reads the whole line as a String and casts it to an Integer.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.