JetBrains Academy: Input streams - Kamil-Jankowski/Learning-JAVA GitHub Wiki

JetBrains Academy: Input streams

Convert to bytes:

Read an input text from the console and print it as a sequence of bytes.

Use System.in as input stream directly. Avoid using Scanner.

import java.io.InputStream;

class Main {
    public static void main(String[] args) throws Exception {
        InputStream inputStream = System.in;
        int current = inputStream.read();
        
        while (current != -1) {
            System.out.print(current);
            current = inputStream.read();
        }
        
        inputStream.close();
    }
}

Reverse input text:

Read an input text from the console and print its characters in reversed order.

Use Reader for collecting characters.

In this task, the input is limited by 50 characters. However, you are welcome to find a solution that does not depend on the input size, which may require some extra knowledge.

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

class Main {
    public static void main(String[] args) throws Exception {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        // start coding here
        char[] chars = new char[50]; // use ArrayList to store not defined amount of characters
        reader.read(chars);        
        reader.close();
        
        for (int i = chars.length - 1; i >= 0; i--) {
            if (chars[i] != '\u0000') {
                System.out.print(chars[i]);
            }
        }
    }
}

Count words:

Read an input text from the console and print the number of words. By word we mean a sequence of characters separated by one or several spaces.

If the input is empty or there are no characters except spaces, print 0.

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

class Main {
    public static void main(String[] args) throws Exception {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        String input = reader.readLine();
        reader.close();
        final String trimmed = input.trim();
        if (trimmed.length() > 0) {
            String[] words = trimmed.split("\\s+");
            System.out.println(words.length);
        } else {
            System.out.println(0);
        }
    }
}