Java Collection How to - Fill an array of characters from user input using Scanner








Question

We would like to know how to fill an array of characters from user input using Scanner.

Answer

import java.util.Scanner;
// w  ww  .j a  v  a  2 s .  c o m
public class Main {
  public static void main(String args[]) {
    Scanner sc = new Scanner(System.in);
    System.out.println("Please enter elements...");
    char[] a = sc.next().toCharArray();
    System.out.println("Array elements are : ");
    for (int i = 0; i < a.length; i++)
      System.out.println(a[i]);
  }
}

The code above generates the following result.