Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
How to Take Array Input in Java?
2.1.
Using Scanner Class & Loops
2.1.1.
Import the Scanner Class
2.1.2.
 
2.1.3.
Define Your Array
3.
Examples
3.1.
Java
4.
Using BufferedReader & InputStreamReader Class
4.1.
Import Necessary Classes
4.2.
Create BufferedReader Instance
4.3.
Read & Store Data
5.
Example
5.1.
Java
6.
Frequently Asked Questions
6.1.
Why use BufferedReader over Scanner for reading array input in Java?
6.2.
How do you handle exceptions when taking array input in Java?
6.3.
Can you use these methods for types other than int?
7.
Conclusion
Last Updated: Mar 27, 2024
Easy

How to take array input from user in java?

Author Rinki Deka
0 upvote
Roadmap to SDE career at Amazon
Speaker
Anubhav Sinha
SDE-2 @
25 Jun, 2024 @ 01:30 PM

Introduction

Arrays are a fundamental concept in programming, especially when dealing with large sets of data. Essentially, an array in Java is a collection of similar types of data stored in contiguous memory locations. It's like having a series of boxes, each holding a piece of data, all lined up in a row. This makes it easy to manage and access the data efficiently.

How to take array input from user in java?

Throughout this article, we'll explore how to input data into arrays in Java, covering practical methods like using the Scanner class & loops, and BufferedReader & InputStreamReader class. 

How to Take Array Input in Java?

Taking input for an array in Java might sound complex at first, but it's pretty straightforward once you get the hang of it. One common way to do this is by using the Scanner class combined with loops. Let's break this down into simpler steps.

Using Scanner Class & Loops

The Scanner class is a part of java.util package, and it's a popular choice for reading input from various sources, including user input from the console. Here’s a step-by-step guide to using the Scanner class to input data into an array:

Import the Scanner Class

Start by importing the java.util.Scanner; this will allow your program to use the functionalities provided by the Scanner class.

import java.util.Scanner;


Create a Scanner Instance: Next, you'll need to create a new Scanner instance. This is like opening a door for your program to accept user input.

Scanner scanner = new Scanner(System.in);

 

Define Your Array

Before you can store anything, you need to tell your program about the array. This includes its type and size. For example, if you want to store five integers, you would do it like this:

int[] myArray = new int[5]; // Array to hold 5 integers


Loop Through the Array: Now, use a loop to go through the array and store input in each position. A for loop works well for this.

for(int i = 0; i < myArray.length; i++) {
    System.out.println("Enter a number: ");
    myArray[i] = scanner.nextInt(); // Storing user input in the array
}


This simple loop runs until it fills every slot in the array with user input. The scanner.nextInt() method reads the next integer from the console and stores it in the array.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Examples

Here's an example to illustrate the process:

  • Java

Java

import java.util.Scanner;

public class ArrayInputExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int[] numbers = new int[5]; // An array to hold 5 integers

// Taking input for the array
for(int i = 0; i < numbers.length; i++) {
System.out.println("Enter number " + (i + 1) + ": ");
numbers[i] = scanner.nextInt();
}

// Displaying the array elements
System.out.println("You entered: ");
for(int num : numbers) {
System.out.println(num);
}
}
}

 

Output

Enter number 1: 
5
Enter number 2: 
5
Enter number 3: 
7
Enter number 4: 
9
Enter number 5: 
10
You entered: 
5
5
7
9
10


In this example, the program prompts the user to enter five numbers, stores them in an array, and then prints out the numbers. It's a simple yet effective way to understand how array inputs work in Java.

Using BufferedReader & InputStreamReader Class

When you need to handle larger inputs or want to optimize performance, the BufferedReader along with InputStreamReader comes into play. This combination provides a more efficient way to read text from the input stream. Let's see how we can use these classes to take array input in Java.

Import Necessary Classes

First, ensure your program knows about the BufferedReader and InputStreamReader by importing them.

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;

Create BufferedReader Instance

To read data, create an instance of BufferedReader. This is done by wrapping an InputStreamReader, which in turn is created by System.in, the standard input stream.

BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));


Define Your Array: Just like before, you need an array. Decide its type and size based on your needs.

int[] myArray = new int[5]; // Array to hold 5 integers

Read & Store Data

Use a loop to read data from the console and store it in your array. BufferedReader reads data line by line, so you'll need to convert the input to the appropriate type, like Integer in this case.

for(int i = 0; i < myArray.length; i++) {
    try {
        System.out.println("Enter a number: ");
        myArray[i] = Integer.parseInt(reader.readLine()); // Reading and storing data
    } catch (IOException e) {
        e.printStackTrace(); // Handling potential IO exceptions
    }
}

Example

Here's a full example that demonstrates how to use BufferedReader and InputStreamReader to input data into an array:

  • Java

Java

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;

public class ArrayInputExample {
public static void main(String[] args) {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
int[] numbers = new int[5]; // An array to hold 5 integers

// Taking input for the array
for(int i = 0; i < numbers.length; i++) {
try {
System.out.println("Enter number " + (i + 1) + ": ");
numbers[i] = Integer.parseInt(reader.readLine());
} catch (IOException e) {
System.out.println("An error occurred. Please try again.");
e.printStackTrace();
}
}

// Displaying the array elements
System.out.println("You entered: ");
for(int num : numbers) {
System.out.println(num);
}
}
}

 

Output

Enter number 1: 
5
Enter number 2: 
5
Enter number 3: 
7
Enter number 4: 
9
Enter number 5: 
10
You entered: 
5
5
7
9
10

 

In this program, the user is prompted to enter five numbers. These numbers are then stored in an array using the BufferedReader and InputStreamReader classes. Finally, the numbers are printed out to demonstrate that they were stored correctly.

This method is particularly useful for reading large amounts of data efficiently. While it might seem a bit more complex due to the need to handle exceptions, it's a valuable tool in your Java toolkit.

Frequently Asked Questions

Why use BufferedReader over Scanner for reading array input in Java?

BufferedReader can handle larger inputs more efficiently than Scanner because it reads data in bulk (larger blocks) rather than parsing it token by token. This can significantly improve performance in input-intensive applications.

How do you handle exceptions when taking array input in Java?

When using BufferedReader, it's common to encounter IOExceptions due to input/output errors. You should surround your input code with a try-catch block to handle these exceptions gracefully, ensuring your program doesn't crash unexpectedly.

Can you use these methods for types other than int?

Absolutely! The examples provided focus on integer arrays, but you can adapt the code to work with any data type. For non-integer types, adjust the parsing method in the input section accordingly (e.g., use Double.parseDouble for double arrays).

Conclusion

In this article, we have learned two primary methods for taking array input in Java, focusing on using the Scanner class with loops and the combination of BufferedReader and InputStreamReader. These methods provide foundational skills for handling user input, an essential part of many Java applications. 

You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. Also, check out some of the Guided Paths on topics such as Data Structure and AlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.

Previous article
Check loop in array according to given constraints
Next article
Difference Between Linear Array And A Record
Live masterclass