Java Array Input Formats – Easy Guide
This guide explains how to read arrays in Java when the input format changes. In coding platforms like
TCS NQT, HackerRank, or LeetCode, arrays can appear in different formats. This document shows simple
ways to handle the most common formats.
Common Input Formats
• [1,2,3,4,5] (Array style format)
• 1 2 3 4 5 (Space separated numbers)
• 1,2,3,4,5 (Comma separated numbers)
• 5 8 10 20 30 40 (Size not given, read until input ends)
1. Reading Array Format Example
Input Example: [1,2,3,4,5]
for (char c : [Link]()) {
if ([Link](c)) {
[Link]([Link](c));
}
}
This method reads each character from the input string. If the character is a digit, it converts it into an
integer and stores it in the ArrayList.
2. Reading Space Separated Numbers
Input Example: 1 2 3 4 5
Scanner ss = new Scanner(input);
while ([Link]()) {
[Link]([Link]());
}
The scanner reads integers separated by spaces and stores them into the list.
3. Reading Comma Separated Numbers
Input Example: 1,2,3,4,5
Scanner ss = new Scanner(input).useDelimiter(",");
while ([Link]()) {
[Link]([Link]());
}
The delimiter is changed to a comma so the scanner splits numbers using commas.
4. Reading When Array Size is Not Given
If the array size is not provided, simply keep reading numbers until the input ends.
Scanner ss = new Scanner(input);
while ([Link]()) {
[Link]([Link]());
}
This method is useful when the problem statement does not provide the number of elements.
Key Idea
In Java, the Scanner class can parse input differently depending on delimiters. Changing delimiters allows
us to easily handle multiple input formats.