java

How to Fill an Array From Keyboard in Java

In this tutorial, we are going to see how to fill an array from the keyboard in Java using the for loop, as well as the Scanner library to invite the user to enter the elements one by one.
 

Program to Fill an Array From Keyboard in Java :
import java.util.Arrays;
import java.util.Scanner;

public class Main {
   public static void main(String args[]) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter the size of the array : ");
      int size = sc.nextInt();
      String tab[] = new String[size];
      
      System.out.println("Enter the array elements (Strings): ");
      for(int i=0; i < size; i++) {
         tab[i] = sc.next();
      }
      System.out.println("The elements of the array" + Arrays.toString(tab));
   }
}

 
Output:

Enter the size of the array :
4
Enter the array elements (Strings):
Java
PHP
C++
C#
The elements of the array [Java, PHP, C++, C#]
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *