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

Java 8Object Oriented ProgrammingProgramming

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]
raja
Published on 08-Jan-2018 12:53:41
Advertisements