- Trending Categories
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]
- Related Articles
- How to read a single character using Scanner class in Java?
- How to switch data from an array to array list in java?
- How to read data from .csv file in Java?
- How to read data from JSON array using JavaScript?
- How to read/write data from/to .properties file in Java?
- How to read the data from a file in Java?
- How to read data in from a file to String using java?
- How to print data of specific element from an array in java?
- How to read a 2d array from a file in java?
- How to read contents of a file using Scanner class?
- How to read data from user using the Console class in Java?
- How to read data from all files in a directory using Java?
- How to read the data from a properties file in Java?\n
- How to read the data from a CSV file in Java?\n
- How to read data from EEPROM in Arduino?

Advertisements