Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to print array 0th element [duplicate]

Tags:

java

arrays

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.

like image 243
Arka Bhattacharjee Avatar asked Dec 11 '13 13:12

Arka Bhattacharjee


3 Answers

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

like image 146
kai Avatar answered Nov 01 '22 02:11

kai


Try this mate:

    input.nextLine();   // gobble the newline
    for (int i = 0; i < size; i++) {
        arr[i] = input.nextLine();
    }
like image 43
vikingsteve Avatar answered Nov 01 '22 02:11

vikingsteve


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

like image 2
Kamlesh Arya Avatar answered Nov 01 '22 04:11

Kamlesh Arya