Reputation: 13
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]
Upvotes: 1
Views: 61
Reputation: 625
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
.
Upvotes: 1
Reputation: 3027
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();
}
Upvotes: 1