Java Stdin and Stdout I | HackerRank Solution

Java Stdin and Stdout I | HackerRank Solution

Java Stdin and Stdout I is about as small as a problem gets: read three integers and print them back, one per line. There is no logic to work out. What it tests is whether you understand where a program's input comes from (standard input, or "stdin") and where its output goes (standard output, or "stdout"), and whether you can use Java's Scanner class to move numbers between the two.

Every online judge, from HackerRank to CodeChef to campus placement tests, works this way. Your program never sees a file name or a text box. It reads from stdin and writes to stdout, and the judge compares what you wrote with the expected answer. If this part is shaky, even a correct algorithm will fail, so it is worth ten minutes now.

Problem

Read three integers from standard input and print each one on its own line, in the same order.

Input format: three lines, each holding a single integer.

Output format: three lines, each holding one of the integers, in input order.

Constraints: the old statement gives none. Ordinary int values are expected.

Input:
42
100
125

Output:
42
100
125

Approach

  1. Create a Scanner that reads from System.in.
  2. Call nextInt() three times and store the results in three variables.
  3. Print each variable with System.out.println(), which adds a newline after each one.

Dry run: the input stream holds 42\n100\n125\n (where \n is the newline character). The first nextInt() reads 42 and stops just before the newline. The second skips that newline, reads 100. The third skips the next newline and reads 125. Then the three println calls print them on separate lines.

You could also print each number right after reading it. On a judge that gives the same result, because the judge only looks at the final output, not when it was produced.

Solution in Java

import java.util.Scanner;

public class Solution {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);

        // nextInt() skips spaces and newlines before each number
        int a = scan.nextInt();
        int b = scan.nextInt();
        int c = scan.nextInt();
        scan.close();

        System.out.println(a);
        System.out.println(b);
        System.out.println(c);
    }
}

Here is what the Java pieces do, in plain language.

  • import java.util.Scanner; tells the compiler where to find the Scanner class. Without it, you get a "cannot find symbol" error.
  • System.in is the stdin stream. When you run the program yourself it is your keyboard. On the judge it is the test file.
  • new Scanner(System.in) wraps that stream. Raw input is just characters; Scanner splits it into "tokens" (pieces separated by whitespace) and converts them to the type you ask for.
  • nextInt() skips any whitespace, reads the next token and turns it into an int. If the token is not a number (say abc), it throws InputMismatchException. If there is no more input, it throws NoSuchElementException.
  • System.out.println(x) writes x to stdout followed by a newline.
  • scan.close() closes the Scanner, and with it System.in. Do it only after all reading is done; you cannot reopen stdin afterwards.

One detail that surprises students: because nextInt() treats spaces and newlines the same way, the program also works if all three numbers come on one line, or if they are spread across lines unevenly. I tested it with the sample and with the input -5 0 on one line and 7 on the next. It printed -5, 0 and 7 on three lines, which shows negatives and zero are handled too.

The solution that was on this page before was already correct. This version is the same idea with a few comments and the Scanner closed after use.

Output

42
100
125

Complexity

O(1) time and O(1) space. The amount of work is fixed at three reads and three prints.

Common mistakes

  • Forgetting the import line, which gives a compile error about Scanner.
  • Using System.out.print instead of println. The numbers come out as 42100125 on one line.
  • Creating a new Scanner for every read. On some judges the first Scanner buffers more input than it uses, so the second one finds nothing left and crashes.
  • Reading numbers with nextLine() and forgetting to convert them with Integer.parseInt(). You end up printing strings, which works here by luck but fails as soon as you need to do maths with them.

Next in the Java track: Java If-Else. For mixed input types, see Java Stdin and Stdout II.

Tip: try to solve the problem yourself before reading the solution. Use the code as a reference to check your approach, and make sure you understand why it works.

More HackerRank solutions All coding problems MCQ practice

Comments

Answered 0/0Correct 0