0% found this document useful (0 votes)
3 views8 pages

Java Scanner Input - Output Guide (For Interviews & Competitive Programming)

The document provides a comprehensive guide on using the Java Scanner class for input and output operations, detailing methods for reading various data types such as integers, doubles, strings, and booleans. It also covers advanced topics like reading arrays, 2D matrices, and dynamic lists, as well as tips for efficient input handling in competitive programming. Additionally, it discusses output formatting and the performance considerations of using Scanner versus BufferedReader for large input sizes.

Uploaded by

dhanush
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views8 pages

Java Scanner Input - Output Guide (For Interviews & Competitive Programming)

The document provides a comprehensive guide on using the Java Scanner class for input and output operations, detailing methods for reading various data types such as integers, doubles, strings, and booleans. It also covers advanced topics like reading arrays, 2D matrices, and dynamic lists, as well as tips for efficient input handling in competitive programming. Additionally, it discusses output formatting and the performance considerations of using Scanner versus BufferedReader for large input sizes.

Uploaded by

dhanush
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 8

Java Scanner Input/Output Guide (for

Interviews & Competitive Programming)


The java.util.Scanner class provides methods to read various data types
from input (e.g., console) in Java. You first create a Scanner object, usually
connected to System.in, like:
Scanner sc = new Scanner(System.in); // Scanner for console input

Then use methods like nextInt(), nextDouble(), nextLine(), etc., to read


values. Remember to sc.close() when done[1][2].

1. Basic Inputs and Outputs


 Integer input: Use nextInt().

Scanner sc = new Scanner(System.in);


System.out.print("Enter an integer: ");
int num = sc.nextInt(); // reads an integer
System.out.println("You entered: " + num);
sc.close();

This reads a whole number and prints it. (Internally nextInt() skips
whitespace and converts the token to int[1].)

 Double input: Use nextDouble().

Scanner sc = new Scanner(System.in);


System.out.print("Enter a double: ");
double d = sc.nextDouble(); // reads a double (e.g. 3.14)
System.out.println("Double: " + d);
sc.close();

nextDouble() parses a floating-point number (with decimal) from


input[3].

 String input (single word): Use next().

Scanner sc = new Scanner(System.in);


System.out.print("Enter a word: ");
String word = sc.next(); // reads the next token (up to
whitespace)
System.out.println("Word: " + word);
sc.close();
next() reads the next word (token) stopping at whitespace.

 String input (full line): Use nextLine().

Scanner sc = new Scanner(System.in);


System.out.print("Enter a line: ");
String line = sc.nextLine(); // reads the entire line
(including spaces)
System.out.println("Line: " + line);
sc.close();

nextLine() reads input until a newline is encountered. It can capture


full sentences with spaces (unlike next()). Note: if mixing nextInt()
and nextLine(), you may need to consume the leftover newline (e.g.,
call an extra nextLine() after nextInt() to clear the buffer).
 Boolean input: Use nextBoolean().

Scanner sc = new Scanner(System.in);


System.out.print("Enter true or false: ");
boolean flag = sc.nextBoolean(); // reads a boolean
System.out.println("Boolean: " + flag);
sc.close();

nextBoolean() parses true or false from input[4].

Each of these methods blocks until valid input is entered; entering the wrong
type (e.g. text when expecting nextInt()) causes an exception. Always guide
the user with a prompt (e.g., System.out.print) so they know what to enter.

2. Multiple Space-Separated Inputs in One Line


Scanner can read multiple values from the same line by calling its methods
in sequence. For example:
 Multiple integers:

Scanner sc = new Scanner(System.in);


System.out.print("Enter two integers separated by space: ");
int a = sc.nextInt();
int b = sc.nextInt(); // both read from one line
System.out.println("Sum = " + (a + b));
sc.close();

If the user types 10 20 and presses Enter, nextInt() reads 10, then the
second nextInt() reads 20. Scanner automatically splits on
whitespace.
 Multiple strings:

Scanner sc = new Scanner(System.in);


System.out.print("Enter two words: ");
String s1 = sc.next();
String s2 = sc.next();
System.out.println("Words: " + s1 + ", " + s2);
sc.close();

If input is Hello World, s1 becomes "Hello" and s2 becomes "World".

 Mixed types:

Scanner sc = new Scanner(System.in);


System.out.print("Enter an integer and a word: ");
int x = sc.nextInt();
String w = sc.next();
System.out.println("Number: " + x + ", Word: " + w);
sc.close();

For input 5 code, this reads integer 5 then string "code".

These patterns are common in coding tests: just keep calling nextInt(),
nextDouble(), next(), etc., in order. Scanner tokenizes input on whitespace
by default.

3. Array Input
Integer array: Read the size, then loop.

Scanner sc = new Scanner(System.in);


System.out.print("Enter size of array: ");
int n = sc.nextInt(); // e.g. 5
int[] arr = new int[n];
System.out.println("Enter " + n + " integers:");
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt(); // read each element
}
// Example: print the array
System.out.println(Arrays.toString(arr));
sc.close();

This reads n integers into an array. (Scanner will accept them space-
separated or newline-separated.) As GeeksforGeeks illustrates, you can use a
loop with nextInt() to fill the array[5].
String array: Similarly, for strings:
Scanner sc = new Scanner(System.in);
System.out.print("Enter number of strings: ");
int n = sc.nextInt();
String[] arr = new String[n];
System.out.println("Enter " + n + " words:");
for (int i = 0; i < n; i++) {
arr[i] = sc.next(); // reads the next word
}
System.out.println(Arrays.toString(arr));
sc.close();

Each next() reads one word into the array. If you need full lines (with
spaces), use nextLine() inside the loop instead.
Arrays can also be read from a single line by reading a line and splitting it.
For example:

String line = sc.nextLine();


String[] parts = line.split(" "); // split by spaces
int[] arr = new int[parts.length];
for (int i = 0; i < parts.length; i++) {
arr[i] = Integer.parseInt(parts[i]);
}

(This reads all space-separated integers in one line and parses them.) The
Scanner approach above is more direct when you know the count.

4. 2D Array (Matrix) Input


To read an m×n integer matrix, first read the dimensions, then use nested
loops:
Scanner sc = new Scanner(System.in);
System.out.print("Enter rows and columns: ");
int m = sc.nextInt();
int n = sc.nextInt();
int[][] mat = new int[m][n];
System.out.println("Enter " + m + "x" + n + " matrix elements:");
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
mat[i][j] = sc.nextInt();
}
}
// Print matrix to verify
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
System.out.print(mat[i][j] + " ");
}
System.out.println();
}
sc.close();

This prompts for dimensions and then reads m*n integers into mat[i][j].
GeeksforGeeks shows the same pattern of nested loops filling a 2D array
with nextInt()[6]. Scanner splits each line’s input into tokens, so it works
whether the user enters all numbers on one line or each row on a new line.

5. List Input (Dynamic Size)


If the number of inputs isn’t known ahead of time, you can use an ArrayList.
For example, to read integers until end-of-input:
Scanner sc = new Scanner(System.in);
List<Integer> list = new ArrayList<>();
System.out.println("Enter integers (end input with non-number):");
while (sc.hasNextInt()) {
list.add(sc.nextInt());
}
// Now list contains all entered integers
System.out.println("List: " + list);
sc.close();

Here, sc.hasNextInt() checks if another integer is available. The loop reads


integers until none remain (e.g. EOF or a non-integer is entered). This lets
your program adapt to any number of inputs. (You could also check for a
sentinel value and break.) Using an ArrayList means the list grows
dynamically as needed.

6. Edge Input Types


 Character input: Scanner has no nextChar() method. To read a single
character, read a string and take its first char:

Scanner sc = new Scanner(System.in);


System.out.print("Enter a character: ");
char ch = sc.next().charAt(0); // take first character of the
next token
System.out.println("Char: " + ch);
sc.close();

This uses next() (reads a word) then .charAt(0). As GeeksforGeeks


notes, this is how to read a character with Scanner[7].

 Long and Float: Similar to other primitives, Scanner provides


nextLong() and nextFloat(). For example:
Scanner sc = new Scanner(System.in);
System.out.print("Enter a long and a float: ");
long L = sc.nextLong(); // reads a long integer
float f = sc.nextFloat(); // reads a float
System.out.println("Read long = " + L + ", float = " + f);
sc.close();

nextLong() and nextFloat() parse the corresponding types[8][9]. You


can use them just like nextInt()/nextDouble() for other numeric types.

7. Output Formats
 System.out.print(...) vs System.out.println(...):
print() writes text without a newline, whereas println() appends a
newline after the text[10]. For example:

System.out.print("Hello ");
System.out.print("World");
// output: Hello World (on same line)

System.out.println("Hello");
System.out.println("World");
// output: Hello [newline] World [newline]

 Formatted output (printf): Use System.out.printf() with format


specifiers (like %d for integers, %s for strings, %n for newline). Example:

String name = "Alice";


int score = 42;
System.out.printf("Name: %s, Score: %d%n", name, score);
// e.g., prints: Name: Alice, Score: 42

This is similar to C’s printf. For instance, System.out.printf("I like


%s!%n", name); uses %s to insert a string[11].

 Printing arrays:

 For a one-dimensional array, the easiest way is Arrays.toString(arr):

int[] arr = {1, 2, 3};


System.out.println(Arrays.toString(arr)); // prints: [1, 2, 3]

This returns a readable string of the array contents[12].


 For 2D arrays, you can either loop through elements, or use
Arrays.deepToString(matrix). Example with loops:
for (int i = 0; i < mat.length; i++) {
for (int j = 0; j < mat[i].length; j++) {
System.out.print(mat[i][j] + " ");
}
System.out.println();
}

This iterates rows and columns to print each element (same as


[26†L113-L121]). Alternatively,
System.out.println(Arrays.deepToString(mat)); will print the entire
2D array in one line (useful for debugging), as it returns a string of the
“deep contents” of the array[13].

8. Competitive Programming Input Tips


 Scanner Speed: Scanner is convenient but relatively slow because it
does parsing and has more overhead[14]. For small to medium input
sizes it’s fine, but in contests with very large input, it may become a
bottleneck. GeeksforGeeks notes that Scanner is “slow and not
recommended for performance-critical tasks”[14].

 Faster I/O: For large inputs, consider using BufferedReader (with


InputStreamReader) or a custom fast reader. For example:

BufferedReader br = new BufferedReader(new


InputStreamReader(System.in));
String line = br.readLine();
StringTokenizer st = new StringTokenizer(line);
int a = Integer.parseInt(st.nextToken());
int b = Integer.parseInt(st.nextToken());

BufferedReader with readLine() is faster because it reads raw lines of


text with minimal parsing overhead[15]. You then manually split or
tokenize the line and parse integers (Integer.parseInt). This requires
more code, but it’s much faster for huge inputs. A common pattern is
to wrap BufferedReader with StringTokenizer or write a custom
FastReader class.

 Using Scanner Efficiently: If you stick with Scanner, you can still
improve performance a bit by:

 Reusing one Scanner object (do not create many).


 Using sc.useDelimiter("\\s+") to ensure it splits on whitespace (the
default).
 Reading entire lines and splitting manually when reading many
numbers in a row (e.g. one large line of numbers).
 Minimizing calls to I/O methods and doing bulk parsing.
In summary, Scanner covers most input needs for interviews and simple
problems. For competitive programming with heavy I/O, be aware of its
speed limits and consider faster alternatives (e.g. [39†L121-L126], [39†L174-
L181]).
Sources: Java Scanner usage and I/O examples are adapted from
GeeksforGeeks and Oracle documentation[1][2][5][6][10][12][16][7][14][13].

[1] [2] [3] [4] [8] [9] Java User Input - Scanner Class - GeeksforGeeks
https://www.geeksforgeeks.org/java/java-user-input-scanner-class/
[5] [6] How to Take Array Input From User in Java? - GeeksforGeeks
https://www.geeksforgeeks.org/java/how-to-take-array-input-from-user-in-
java/
[7] Scanner and nextChar() in Java - GeeksforGeeks
https://www.geeksforgeeks.org/java/gfact-51-java-scanner-nextchar/
[10] [11] Java's print vs println method: What's the difference?
https://www.theserverside.com/blog/Coffee-Talk-Java-News-Stories-and-
Opinions/println-vs-print-difference-printf-Java-newline-when-to-use
[12] Simplest Method to Print Array in Java - GeeksforGeeks
https://www.geeksforgeeks.org/java/simplest-method-to-print-array-in-java/
[13] Java Arrays Deep ToString Method
https://www.tutorialspoint.com/java/util/arrays_deeptostring.htm
[14] [15] Fast I/O in Java in Competitive Programming - GeeksforGeeks
https://www.geeksforgeeks.org/competitive-programming/fast-io-in-java-in-
competitive-programming/
[16] Print a 2D Array or Matrix in Java | GeeksforGeeks
https://www.geeksforgeeks.org/print-2-d-array-matrix-java/

You might also like