How to read data from scanner to an array in java?


The Scanner class of the java.util package gives you methods like nextInt(), nextByte(), nextFloat() etc. to read data from keyboard. To read an element of an array uses these methods in a for loop:

Example

 Live Demo

import java.util.Arrays;
import java.util.Scanner;

public class ReadingWithScanner {
   public static void main(String args[]) {
      Scanner s = new Scanner(System.in);
      System.out.println("Enter the length of the array:");
      int length = s.nextInt();
      int [] myArray = new int[length];
      System.out.println("Enter the elements of the array:");

      for(int i=0; i<length; i++ ) {
         myArray[i] = s.nextInt();
      }

      System.out.println(Arrays.toString(myArray));
   }
}

Output

Enter the length of the array:
5
Enter the elements of the array:
25
56
48
45
44
[25, 56, 48, 45, 44]

Updated on: 30-Jul-2019

10K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements