Sir i am trying to print array's 0th element but i can't. Here is my code
import java.util.Scanner;
public class prog3
{
public static void main (String[] args){
Scanner input = new Scanner(System.in);
int size = input.nextInt();
String arr[] = new String[size];
for (int i=0; i<size; i++){
arr[i]= input.nextLine();
}
System.out.print(arr[0]);
}
}
when i am trying to print arr[0]
its return blank but when i print arr[1]
it returns the 0th element value. would you please help me to find my error.
Change
arr[i]= input.nextLine();
to
arr[i]= input.next();
and it works. this is because nextLine(
) reads a whitespace and then it looks like arr[0]
is empty. You can see this, because if the size
is 3 you can input only two times. See http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html for more information about scanner :)
Try this mate:
input.nextLine(); // gobble the newline
for (int i = 0; i < size; i++) {
arr[i] = input.nextLine();
}
Corrected code: Include input.nextLine();
after input.nextInt()
import java.util.Scanner;
public class prog3{
public static void main (String[] args){
Scanner input = new Scanner(System.in);
int size = input.nextInt();
input.nextLine();
String arr[] = new String[size];
for (int i=0; i<size; i++){
arr[i]= input.nextLine();
}
System.out.print(arr[0]);
}
}
Input :
2
45
95
Output
45
Explanation:
The problem is with the input.nextInt() command it only reads the int value. So when you continue reading with input.nextLine() you receive the "\n" Enter key. So to skip this you have to add the input.nextLine(). Scanner issue when using nextLine after nextXXX
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With