search
HomeBackend DevelopmentGolangReading data from standard input (stdin)

Lendo dados da entrada padrão (stdin)

For those who are not following POJ (Pascal on the JVM) it is a compiler that transforms a subset from Pascal to JASM (Java Assembly) so that we can use the JVM as an execution environment.

In the last post, contexts (from parser) and nested sentences were discussed. In this publication we will talk about the changes necessary to make it possible to read data from standard input (stdin), using the read/readln function from Pascal.

As we are compiling for the JVM, it is necessary to detail the functioning of various points of this incredible virtual machine. Therefore, at various times I detail the internal functioning of the JVM as well as some of its instructions (opcodes).

Reading data from stdin (standard input)

Standard input (stdin) is the stream from which a program reads its input data. Until now we only supported stdout (standard output).

In this commit a Java program was implemented to understand how the JVM deals with stdin:

public class InputData {
    public static String name;
    public static int age;

    public static void main(String[] args) {
        name = System.console().readLine();
        age = Integer.parseInt(System.console().readLine());
        System.out.println("You entered string " + name);
    }

When we disassemble the file class we get the assembly below. Irrelevant snippets were omitted, and the original snippet (in Java) that gave rise to assembly was inserted with ";;":

 1: public class InputData {
 2:     ;; public static String name;
 3:     public static name java/lang/String
 4: 
 5:     ;; public static int age;
 6:     public static age I
 7:
 8:     public static main([java/lang/String)V {
 9:         ;; name = System.console().readLine();
10:         invokestatic java/lang/System.console()java/io/Console
11:         invokevirtual java/io/Console.readLine()java/lang/String
12:         putstatic InputData.name java/lang/String
13:
14:         ;; age = Integer.parseInt(System.console().readLine());
15:         invokestatic java/lang/System.console()java/io/Console
16:         invokevirtual java/io/Console.readLine()java/lang/String
17:         invokestatic java/lang/Integer.parseInt(java/lang/String)I
18:         putstatic InputData.age I
19:
20:         ;; System.out.println("You entered string " + name);
21:         getstatic java/lang/System.out java/io/PrintStream
22:         getstatic InputData.name java/lang/String
23:         invokedynamic makeConcatWithConstants(java/lang/String)java/lang/String {
                invokestatic java/lang/invoke/StringConcatFactory.makeConcatWithConstants(java/lang/invoke/MethodHandles$Lookup, java/lang/String, java/lang/invoke/MethodType, java/lang/String, [java/lang/Object)java/lang/invoke/CallSite
                ["You entered string "]
            }
24:
25:         invokevirtual java/io/PrintStream.println(java/lang/String)V
26:
27:         return
    }
}

With this example it was possible to identify that to read data from stdin it was necessary to use the System.console().readLine() instruction (lines 11 and 16). And since readLine() returns a string, to read numbers it was necessary to convert using the function Integer.parseInt (line 17).

That said, from the Pascal program below:

program NameAndAge;
var
    myname: string;
    myage: integer;
begin
    write('What is your name? '); readln(myname);
    write('How old are you? '); readln(myage);
    writeln;
    writeln('Hello ', myname);
    writeln('You are ', myage, ' years old');
end.

POJ has been adjusted to generate the following JASM:

// Code generated by POJ 0.1
public class name_and_age {
    ;; var myname: string;
    public static myname java/lang/String

    ;; var myage: integer;
    public static myage I

    ;; procedure main
    public static main([java/lang/String)V {
        ;; write('What is your name? ');
        getstatic java/lang/System.out java/io/PrintStream
        ldc "What is your name? "
        invokevirtual java/io/PrintStream.print(java/lang/String)V

        ;; readln(myname);
        invokestatic java/lang/System.console()java/io/Console
        invokevirtual java/io/Console.readLine()java/lang/String
        putstatic name_and_age.myname java/lang/String

        ;; write('How old are you? ');
        getstatic java/lang/System.out java/io/PrintStream
        ldc "How old are you? "
        invokevirtual java/io/PrintStream.print(java/lang/String)V

        ;; readln(myage);
        invokestatic java/lang/System.console()java/io/Console
        invokevirtual java/io/Console.readLine()java/lang/String
        invokestatic java/lang/Integer.parseInt(java/lang/String)I
        putstatic name_and_age.myage I

        ;; writeln;
        getstatic java/lang/System.out java/io/PrintStream
        invokevirtual java/io/PrintStream.println()V

        ;; writeln('Hello ', myname);
        getstatic java/lang/System.out java/io/PrintStream
        ldc "Hello "
        invokevirtual java/io/PrintStream.print(java/lang/String)V
        getstatic java/lang/System.out java/io/PrintStream
        getstatic name_and_age.myname java/lang/String
        invokevirtual java/io/PrintStream.print(java/lang/String)V
        getstatic java/lang/System.out java/io/PrintStream
        invokevirtual java/io/PrintStream.println()V

        ;; writeln('You are ', myage, ' years old');
        getstatic java/lang/System.out java/io/PrintStream
        ldc "You are "
        invokevirtual java/io/PrintStream.print(java/lang/String)V
        getstatic java/lang/System.out java/io/PrintStream
        getstatic name_and_age.myage I
        invokevirtual java/io/PrintStream.print(I)V
        getstatic java/lang/System.out java/io/PrintStream
        ldc " years old"
        invokevirtual java/io/PrintStream.print(java/lang/String)V
        getstatic java/lang/System.out java/io/PrintStream
        invokevirtual java/io/PrintStream.println()V

        return
    }
}

This commit implements the necessary changes to the POJ parser.

Here is the full PR.

Next steps

In the next publication we will complete one of the objectives of this project: calculating the factorial recursively.

Complete project code

The repository with the project's complete code and documentation is here.

The above is the detailed content of Reading data from standard input (stdin). For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Learn Go String Manipulation: Working with the 'strings' PackageLearn Go String Manipulation: Working with the 'strings' PackageMay 09, 2025 am 12:07 AM

Go's "strings" package provides rich features to make string operation efficient and simple. 1) Use strings.Contains() to check substrings. 2) strings.Split() can be used to parse data, but it should be used with caution to avoid performance problems. 3) strings.Join() is suitable for formatting strings, but for small datasets, looping = is more efficient. 4) For large strings, it is more efficient to build strings using strings.Builder.

Go: String Manipulation with the Standard 'strings' PackageGo: String Manipulation with the Standard 'strings' PackageMay 09, 2025 am 12:07 AM

Go uses the "strings" package for string operations. 1) Use strings.Join function to splice strings. 2) Use the strings.Contains function to find substrings. 3) Use the strings.Replace function to replace strings. These functions are efficient and easy to use and are suitable for various string processing tasks.

Mastering Byte Slice Manipulation with Go's 'bytes' Package: A Practical GuideMastering Byte Slice Manipulation with Go's 'bytes' Package: A Practical GuideMay 09, 2025 am 12:02 AM

ThebytespackageinGoisessentialforefficientbyteslicemanipulation,offeringfunctionslikeContains,Index,andReplaceforsearchingandmodifyingbinarydata.Itenhancesperformanceandcodereadability,makingitavitaltoolforhandlingbinarydata,networkprotocols,andfileI

Learn Go Binary Encoding/Decoding: Working with the 'encoding/binary' PackageLearn Go Binary Encoding/Decoding: Working with the 'encoding/binary' PackageMay 08, 2025 am 12:13 AM

Go uses the "encoding/binary" package for binary encoding and decoding. 1) This package provides binary.Write and binary.Read functions for writing and reading data. 2) Pay attention to choosing the correct endian (such as BigEndian or LittleEndian). 3) Data alignment and error handling are also key to ensure the correctness and performance of the data.

Go: Byte Slice Manipulation with the Standard 'bytes' PackageGo: Byte Slice Manipulation with the Standard 'bytes' PackageMay 08, 2025 am 12:09 AM

The"bytes"packageinGooffersefficientfunctionsformanipulatingbyteslices.1)Usebytes.Joinforconcatenatingslices,2)bytes.Bufferforincrementalwriting,3)bytes.Indexorbytes.IndexByteforsearching,4)bytes.Readerforreadinginchunks,and5)bytes.SplitNor

Go encoding/binary package: Optimizing performance for binary operationsGo encoding/binary package: Optimizing performance for binary operationsMay 08, 2025 am 12:06 AM

Theencoding/binarypackageinGoiseffectiveforoptimizingbinaryoperationsduetoitssupportforendiannessandefficientdatahandling.Toenhanceperformance:1)Usebinary.NativeEndianfornativeendiannesstoavoidbyteswapping.2)BatchReadandWriteoperationstoreduceI/Oover

Go bytes package: short reference and tipsGo bytes package: short reference and tipsMay 08, 2025 am 12:05 AM

Go's bytes package is mainly used to efficiently process byte slices. 1) Using bytes.Buffer can efficiently perform string splicing to avoid unnecessary memory allocation. 2) The bytes.Equal function is used to quickly compare byte slices. 3) The bytes.Index, bytes.Split and bytes.ReplaceAll functions can be used to search and manipulate byte slices, but performance issues need to be paid attention to.

Go bytes package: practical examples for byte slice manipulationGo bytes package: practical examples for byte slice manipulationMay 08, 2025 am 12:01 AM

The byte package provides a variety of functions to efficiently process byte slices. 1) Use bytes.Contains to check the byte sequence. 2) Use bytes.Split to split byte slices. 3) Replace the byte sequence bytes.Replace. 4) Use bytes.Join to connect multiple byte slices. 5) Use bytes.Buffer to build data. 6) Combined bytes.Map for error processing and data verification.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor