Java Stdin and Stdout I Hackerrank Solution
java 7
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextInt()) {
int number = scanner.nextInt();
System.out.println(number);
}
scanner.close();
}
}
java 8
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
scanner.useDelimiter("\\R");
while (scanner.hasNextInt()) {
int number = scanner.nextInt();
System.out.println(number);
}
scanner.close();
}
}
java 15
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextInt()) {
int number = scanner.nextInt();
System.out.println(number);
}
scanner.close();
}
}
Code Explanation
The solutions start by creating a Scanner object scanner to read input from stdin.
In the Java 8 solution, the scanner.useDelimiter("\\R") line sets the delimiter to match any line terminator, allowing the scanner to read integers from multiple lines.
The solutions then enter a while loop that checks if there is another integer available using scanner.hasNextInt().
Inside the loop, the solutions read the next integer using scanner.nextInt() and store it in the number variable.
The solutions then print the number variable to stdout using System.out.println(number).
In the Java 15 solution, scanner.nextLine() is used after printing each number to consume the remaining characters on the line, allowing the scanner to move to the next line.
The loop continues until there are no more integers available to read, at which point the scanner.hasNextInt() condition becomes false, and the loop exits.
Finally, the solutions close the scanner object to release the resources.