![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
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]
Advertisements