5

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.

albusshin
  • 3,530
  • 2
  • 25
  • 54

3 Answers3

5

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 :)

kai
  • 6,219
  • 16
  • 37
2

Try this mate:

    input.nextLine();   // gobble the newline
    for (int i = 0; i < size; i++) {
        arr[i] = input.nextLine();
    }
vikingsteve
  • 34,284
  • 19
  • 101
  • 142
  • the `nextLine()` method is a bit quirky, since there was a newline "hanging" after `nextInt()`. If you gobble it up, things should then work as you expect. – vikingsteve Dec 11 '13 at 13:17
2

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

Community
  • 1
  • 1
Kamlesh Arya
  • 4,334
  • 2
  • 17
  • 26